Traversing single linked list not working why? - c

im starting to learn data structures and i tried to making a simple program about a single linked list.
The problem is that when i call my display function (transversing the list) it doesn't give me an output? What is wrong with my code and how do i fix this?
This my program:
int main(){
int n;
printf(" Input the number of nodes : ");
scanf("%d", &n);
create(n);
printf("\n Data entered in the list : \n");
display();
}
void create(int n)
{
struct node *head=NULL;
int data, i;
head = (struct node *)malloc(sizeof(struct node));
if(head == NULL)
{
printf(" Memory can not be allocated.");
}
else
{
printf(" Input data for node 1 : ");
scanf("%d", &data);
head->data = data;
head->next = NULL;
for(i=1; i<n; i++) // Creating n nodes
{
struct node *current = (struct node *)malloc(sizeof(struct node)); // addnode
if(current == NULL)
{
printf(" Memory can not be allocated.");
break;
}
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &data);
current->data = data;
current->next = NULL;
head->next = current;
head = head->next;
}
}
}
}
My Traversing function:
void display(struct node *head)
{
struct node* ptr = head;
if(head == NULL)
{
printf(" List is empty.");
}
else
{
while(ptr != NULL)
{
printf(" Data = %d\n", ptr->data);
ptr = ptr->next;
}
}
}

The problem are lines in create()
head->next = current;
head = head->next;
this operation set head to current. Note that current->next is NULL. As result the entire content of the list is lost except the last element.
Just replace those lines with:
current->next = head;
head = current;
This will put the current node at the top of the list.
Remember to return head from create().

#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * next;
};
struct node * create(int n) {
struct node *head=NULL;
int data, i;
struct node * ptmp = NULL;
head = (struct node *)malloc(sizeof(struct node));
if(head == NULL) {
printf(" Memory can not be allocated.");
} else {
printf(" Input data for node 1 : ");
scanf("%d", &data);
head->data = data;
head->next = NULL;
ptmp = head;
for(i=1; i<n; i++) {
struct node *current = (struct node *)malloc(sizeof(struct node)); // addnode
if(current == NULL) {
printf(" Memory can not be allocated.");
break;
} else {
printf(" Input data for node %d : ", i);
scanf(" %d", &data);
#if 0
// insert first
current->data = data;
current->next = head;
head = current;
#else
// insrt last
current->data = data;
current->next = NULL;
ptmp->next=current;
ptmp = current;
#endif
}
}
}
return head;
}
void display(struct node *head)
{
struct node* ptr = head;
if(head == NULL) {
printf(" List is empty.");
} else {
while(ptr != NULL) {
printf(" Data = %d\n", ptr->data);
ptr = ptr->next;
}
}
}
int main() {
int n = 0;
printf(" Input the number of nodes : ");
scanf("%d", &n);
if (n<=0 || n > 6400) {
printf("Invalid input : %d (Enter value in range 0-6400)\n", n);
return 0;
}
struct node * head = create(n);
printf("\n Data entered in the list : \n");
display(head);
}

Related

Keep printing the last element in the linked list

I created a standard linked list in C. It asks the user to input a number, and program end if user input #. If the user inputs anything else the program will stop.
The problem is that my program runs forever and prints the normal list at first then keeping print the last element of the linked list.
Hope someone could tell me where did I made mistake.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} NodeT;
void freeLL(NodeT *list) {
NodeT *p, *temp;
p = list;
while (p != NULL) {
temp = p->next;
free(p);
p = temp;
}
}
void showLL(NodeT *list) {
NodeT *temp = list;
temp = temp->next;
printf("Done. The list is ");
printf("%d", temp->data);
temp = temp->next;
//iterate the entire linked list and print the data
while (temp != NULL) {
printf("-->");
printf("%d", temp->data);
temp = temp->next;
}
}
NodeT *joinLL(NodeT *list, int v) {
NodeT *current = list;
NodeT *head;
head->data = v;
head->next = NULL;
while (current->next != NULL) {
current = current->next;
}
current->next = head;
return head;
}
int main() {
int data;
NodeT *list = NULL;
list = (NodeT *)malloc(sizeof(NodeT));
printf("Enter a number: ");
if (scanf("%d", &data) != 1) {
printf("Done. ");
} else {
printf("Enter a number: ");
joinLL(list, data);
while (1 == scanf("%d", &data)) {
printf("Enter a number: ");
joinLL(list, data);
}
showLL(list);
freeLL(list);
}
return 0;
}
I believe the problem is in the joinLL function which add a new node at the end of the linked list.
The problem is you do not allocate elements in joinLL: only a single element in allocated in main().
You should instead always allocate the element in joinLL and update the head pointer from the return value.
Similary, freeLL should take a pointer to head and set it to NULL for consistency.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} NodeT;
void freeLL(NodeT *p) {
while (p != NULL) {
NodeT *temp = p->next;
free(p);
p = temp;
}
}
void showLL(const NodeT *list) {
NodeT *p = list;
printf("The list is ");
if (p == NULL) {
printf("empty");
} else {
printf(" %d", temp->data);
while ((p = p->next) != NULL) {
printf("--> %d", temp->data);
}
}
printf("\n");
}
NodeT *joinLL(NodeT *head, int v) {
NodeT *newp = malloc(sizeof(*p));
NodeT *current;
if (newp == NULL) {
fprintf(stderr, "allocation failure\n");
exit(1);
}
newp->data = v;
newp->next = NULL;
if (head == NULL) {
return newp;
}
for (current = head; current->next != NULL; current = current->next)
continue;
current->next = newp;
return head;
}
int main() {
NodeT *list = NULL;
for (;;) {
int data;
printf("Enter a number: ");
if (scanf("%d", &data) != 1) {
printf("Done. ");
break;
}
list = joinLL(list, data);
}
showLL(list);
freeLL(list);
return 0;
}
Your program keeps running because of a memory access error, you did not allocate memory for your head(you set a pointer, but use it directly without initializing it)
Change to this may solve the problem:
head=(NodeT*)malloc(sizeof(NodeT));
if(NULL==head)
{
// failed : do something...
return NULL;
}
head->data=v;
head->next=NULL;
When I just tested it, I found that there was another problem:
list = (NodeT*)malloc(sizeof(NodeT));
malloc will not be initialize your list, so the value that your list->next initially points to is uncertain.
in c, malloc does not need to be cast.

In linked list ,when i write (temp->next=newnode) then when i apply temp=temp->next does not work but temp=newnode works?

Below is my code:
#include <stdio.h>
#include <stdlib.h>
int main() {
struct node {
int data;
struct node *next;
};
int choice;
struct node *head, *newnode, *temp;
head = 0;
while (choice) {
newnode = (struct node *)malloc(sizeof(struct node));
printf("enter items ");
scanf("%d", &newnode->data);
newnode->next = 0;
if (head == 0) {
head = temp = newnode;
} else
temp->next = newnode; /** **this is the problem** **/
temp = newnode; /** temp=newnode works but temp=temp->next doesn't**/
printf("do you want to continue");
scanf("%d", &choice);
}
temp = head;
while (temp != 0) {
printf("list is %d \n", temp->data);
temp = temp->next;
}
}
The problem is here:
if(head==0)
{
head=temp=newnode;
}
else
temp->next=newnode; /** **this is the problem** **/
temp=newnode; /** temp=newnode works but temp=temp->next doesn't**/
Indentation does not determine structure. You must enclose multiple instructions in a block to group them in the else clause. As coded, temp=newnode; is executed unconditionally after the test, which is not a problem, but redundant with head=temp=newnode.
Note also that choice is uninitialized when tested the first time.
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int main() {
struct node {
int data;
struct node *next;
};
int choice;
struct node *head, *tail, *newnode, *temp;
head = tail = NULL;
for (;;) {
newnode = (struct node *)malloc(sizeof(struct node));
if (newnode == NULL)
break;
printf("enter item: ");
if (scanf("%d", &newnode->data) != 1) {
free(nownode);
break;
}
newnode->next = NULL;
if (head == NULL) {
head = newnode;
} else {
tail->next = newnode;
}
tail = newnode;
printf("do you want to continue? [0/1] ");
if (scanf("%d", &choice) != 1 || choice == 0)
break;
}
for (temp = head; temp != NULL; temp = temp->next) {
printf("list is %d \n", temp->data);
}
return NULL;
}

make a list of m nodes, where m is taken in input

Hi this is the code I wrote for create as many nodes as he needs (the m variable), but I noticed that using this method I'm creating one more node. What's the best way of fcreating as many nodes as the user say us?
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int val;
int rip;
struct Node *next;
} node;
node *modify(node *head);
void print(node *head2);
int main(){
int m, i;
printf("How many nodes: \n");
scanf("%d", &m);
node *head = NULL;
head = (node *)malloc(sizeof(node));
node *temp = head;
node *head2 = NULL;
printf("Write the value in HEAD position : \n");
scanf("%d", &temp->val);
temp->rip=0;
temp->next = NULL;
for(i=0; i < m-1; i++)
{
temp->next = (node *)malloc(sizeof(node));
printf("Write the value in position %d: \n", i);
temp = temp->next;
scanf("%d", &temp->val);
temp->rip=0;
temp->next = NULL;
}
head2 = modify(head);
print(head2);
return 0;
}
node *modify(node *head){
int counter, pass, m;
node *curr = head;
node *track = head;
node *precNode;
while (track != NULL){
counter = 0;
pass = 0;
m = track->val;
while( curr != NULL){
if(m == (curr)->val){
pass++;
counter++;
if(pass > 1){
node *removed = curr;
precNode->next = (curr)->next;
curr = (curr)->next;
free(removed);
}
if(pass == 1)
{
precNode = curr;
curr = curr->next;
}
}
else{
precNode = curr;
curr = (curr)->next;
}
}
track->rip = counter;
track = track->next;
curr = track;
}
return head;
}
void print(node *head2){
while(head2 != NULL){
printf("[%d, %d] -> ", head2->val, head2->rip);
head2 = head2->next;
}
printf("\n");
}
```

C Linked List Add Item at the End

I'm writing a program that adds a node at the end of an existing linked list.
The problem is that it doesn't seem to assign to the variable nr of struct node of the last element of the linked list the hard coded value 7.
Here is the code:
#include<stdio.h>
#include<stdlib.h>
struct node {
int nr;
struct node *next;
};
void addNodes(struct node **head, int n);
void displayList(struct node *head);
void addItemLast(struct node *head);
int main() {
struct node* head = NULL;
int n;
printf("Introduceti numarul de noduri: ");
scanf("%d", &n);
addNodes(&head, n);
displayList(head);
addItemLast(head);
displayList(head);
return 0;
}
void addNodes(struct node **head, int n) {
*head = (struct node*)malloc(sizeof(struct node));
struct node *current = *head;
printf("\nIntroduceti %d noduri:\n", n);
for(int i = 0; i < n; i++) {
printf("Element %d = ", i+1);
scanf("%d", &(current -> nr));
current->next = (struct node*)malloc(sizeof(struct node));
current = current->next;
}
current->next = NULL;
}
void displayList(struct node *head) {
struct node *current = head;
int i = 1;
printf("\nElementele introduse sunt:\n");
while(current->next != NULL) {
printf("Elementul %d = %d\n", i, current->nr);
current = current->next;
i++;
}
}
void addItemLast(struct node *head) {
struct node *temp = head, *last;
last = (struct node*)malloc(sizeof(struct node));
if(last == NULL) {
printf("\nMemory cannot be allocated!\n");
} else {
last->nr = 7;
last->next = NULL;
while(1) {
if(temp->next == NULL) {
temp->next = last;
break;
}
temp = temp->next;
}
}
}
The last function, addItemLast(), doesn't work as expected.
This is the output:
Introduceti numarul de noduri: 3
Introduceti 3 noduri:
Element 1 = 1
Element 2 = 2
Element 3 = 3
Elementele introduse sunt:
Elementul 1 = 1
Elementul 2 = 2
Elementul 3 = 3
After the function with the problem runs, I get this output:
Elementele introduse sunt:
Elementul 1 = 1
Elementul 2 = 2
Elementul 3 = 3
Elementul 4 = 13383248
Element 4 does not contain the hard coded value 7, but instead has a garbage value and I can't figure out why.
Your implemenation of addNodes is incorrect, suppose I enter n = 2 , 3 nodes are created but only twice scanf function is called, so as result you have garbage value in some node (nr is not set).
Reimplement it (it works if addItemLast function is properly implemented) :
void addNodes(struct node **head, int n){
printf("\nIntroduceti %d noduri:\n", n);
for(int i = 0; i < n; i++){
struct node* last = addItemLast(*head);
if (*head == NULL)
*head = last;
printf("Element %d = ", i);
scanf("%d", &(last -> nr));
}
}
You need to change addItemLast to handle case when you want to call this function but head is NULL (without testing this case your program crashes while calling addItemLast for empty List):
struct node* addItemLast(struct node *head){
struct node *temp = head, *last;
last = (struct node*)malloc(sizeof(struct node));
if (head == NULL) // <---------
{
last->nr = 7;
last->next = NULL;
return last;
}
if(last == NULL){
printf("\nMemory cannot be allocated!\n");
}else{
last->nr = 7;
last->next = NULL;
while(1){
if(temp->next == NULL){
temp->next = last;
break;
}
temp = temp->next;
}
}
return last;
}
and finally function to display list should be:
void displayList(struct node *head){
struct node *current = head;
int i = 1;
printf("\nElementele introduse sunt:\n");
while(current != NULL){ // <---------
printf("Elementul %d = %d\n", i, current->nr);
current = current->next;
i++;
}
}
You do not have to check if current->next != NULL when accessing the element of current.
Change your while loop to:
while(current != NULL){
printf("Elementul %d = %d\n", i, current->nr);
current = current->next;
i++;
}

C: Linked List via Pointers, The build keeps failing for some reason

I coded a basic linked list working by pointers. It has functions for creating, inserting, deleting, and finding nodes according to positions.
For some reason, the build output says
1>Done building project "Linked List.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
There are no errors unfortunately, so I don't understand what's the problem.
Does anyone see what I'm missing here?
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} node;
struct node *head = NULL;
void PrintList()
{
struct node *temp = (node*)malloc(sizeof(node));
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
node* New(int data)
{
node *new = (node*)malloc(sizeof(node));
if (new == NULL)
{
printf("Error \n");
exit(0);
}
new->data = data;
new->next = NULL;
return new;
}
void Create(int data)
{
node *temp = head;
while (temp->next != NULL)
temp = temp->next;
node *new = New(data);
temp->next = new;
}
void Insert(int data, int position)
{
struct node *temp1 = (struct node*)malloc(sizeof(struct node*));
temp1->data = data;
temp1->next = NULL;
if (position == 0)
{
temp1->next = head;
head = temp1;
return;
}
struct node *temp2 = (struct node*)malloc(sizeof(struct node*));
for (int i = 0; i < position - 2; i++)
{
temp2 = temp2->next;
temp2->next = temp1;
}
}
void Delete(int position)
{
struct node *temp1 = (struct node*)malloc(sizeof(struct node*));
if (position == 0)
{
head = temp1->next;
free(temp1);
return;
}
for (int i = 0; i < position - 2; i++)
temp1 = temp1->next;
struct node *temp2 = temp1->next;
temp1->next = temp2->next;
free(temp2);
}
int Find(int position)
{
struct node *temp = (node*)malloc(sizeof(node));
for (int i = 0; i < position + 1; i++)
temp = temp->next;
return temp->data;
free(temp);
}
void menu()
{
printf("Linked List in C \n\n");
printf("1.Create an element\n");
printf("2.Insert as the kth element\n");
printf("3.Delete the kth element\n");
printf("4.Find the kth element\n");
printf("0.Exit\n");
}
int main()
{
int command;
int data;
int position;
head = NULL;
menu();
while (1)
{
printf("\nEnter a command (0~4):");
scanf("%d", &command);
if (command == 0)
break;
switch (command)
{
case 1:
printf("Enter a number to be created as the last element: \n");
scanf("%d", data);
Create(data);
PrintList();
break;
case 2:
printf("Enter a number to insert into the list: \n");
scanf("%d", data);
printf("Enter the position to insert this element: \n");
scanf("%d", position);
Insert(data, position);
PrintList();
break;
case 3:
printf("Enter the position of the element to be deleted: \n");
scanf("%d", position);
Delete(position);
PrintList();
break;
case 4:
printf("Enter the position of the element you are looking for: \n");
scanf("%d", position);
int X = Find(position);
printf("The element in node %d is %d. \n", position, X);
PrintList();
break;
}
}
//dispose(head);
return 0;
}

Resources