display function Link-list code not working - singly-linked-list

im trying to add node at the starting of linked list but in my code it only displaying the last element which i have entered only the last element .what is the problem why this is happening
#include <stdio.h>
//node structure
struct node
{
int data;
struct node *next;
};
//struct
//datatype declaration
typedef struct node node ;
// head pointer which will indicate starting point of link list
node *head;
//create fuction that will insert values into note and its next pointer field
void create(int num);
//display function will display the link list
void display();
main()
{
int num,i,n;
printf("enter the nno of node to create : ");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf("enter data for node %d= ",i+1);
scanf("%d",&num);
create(num);
}
display();
//display call
}
void create(int num)
{
head=NULL;
node *temp;
temp=(node*)malloc(sizeof(node));
temp->data=num;
temp->next=head;
head=temp;
return;
}
//function create() end
void display()
{
node *temp1;
temp1=head;
while(temp1!=NULL)
{
printf("data : %d-> ",temp1->data);
temp1=temp1->next;
}
return;
}
//fucntion display() end

Your main problem is:
head=NULL;
Thus your line
temp->next=head;
always sets the next to be NULL. Thus all your lists are
of length one.
I would suggest either declaring head to be static (and
hence zeroed from the outset), or intializing head in main.

Your display function seems fine, your create function should look something like this:
void create(int num)
{
node* temp = new node();
if(head ==NULL)
{ temp->data = num;
head = temp;
head->next = NULL;
}
else if(head->next == NULL)
{
temp->data = num;
head->next = temp;
}
else
{
node* temp2 = head;
while(temp2->next !=NULL)
{ temp2 = temp2->next;
}
temp->data = num;
temp2->next = temp;
}
return;
}
This create function above will place the node depending if the list is empty, has one node, or more than one node will insert at Last position. You can now go off this to insert in front of head, or in Link list terms function (InsertBeforeFirst). And of course where you have node* head up top should be initialized to NULL;

Related

implementing a linked list and it doesn't produce output

I am implementing a linked list but it doesn't display any output.
implementing a linked list with 4 elements and making fuction insert and insertathead and display.
#include <bits/stdc++.h>
using namespace std;
// class node to make node element.
class node
{
public:
int data;
node *next;
node{
}
// constructor
node(int val)
{
data = val;
next = NULL;
}
// function to insert element at head.
void insertAthead(node *&head, int val)
{
node *n = new node(val);
n->next = head;
head = n;
return;
}
// function to insert in linked list.
void insert(node *head, int val)
{
node *temp = head;
if (head == NULL)
{
insertAthead(head, val);
return;
}
node *n = new node(val);
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = n;
}
// function to display each element in a linked list.
void display(node *head)
{
while (head->next != NULL)
{
cout << head->data;
head = head->next;
}
cout << head->data;
}
};
//main function
int main()
{
node *head; // line at which I think there is a problem
head->insert(head, 1);
head->insert(head, 2);
head->insert(head, 3);
head->insert(head, 4);
head->display(head);
return 0;
}
I think the problem is at line 1
node *head;
when I change this line with node *head=new node(any integer value) the code runs fine.
First you want to move insert, insertAtHead and display out of the Node class. These are list functions have have no need of special access to Node.
Also you should initialise head to NULL (representing the empty list).
This means changing main like this
node *head = NULL;
insert(head, 1);
insert(head, 2);
insert(head, 3);
insert(head, 4);
display(head);
Then you want to change
void insert(node *head, int val)
to
void insert(node *&head, int val)
Just like you have done (correctly) with insertAtHead.
If you wanted to take this further you could create a List class, along these lines
class List
{
public:
List() { root = NULL; }
void insert(int val);
void insertAtHead(int val);
void display();
private:
Node* root;
};
then main would look like this
int main()
{
List l;
l.insert(1);
l.insert(2);
l.insert(3);
l.insert(4);
l.display();
}

Why it is printing only 1st value of doubly linked list and than my program is crashing

I am trying to create a doubly linked list and then printing its value but the output is showing only first value and then the whole program is crashing.
I can't understand where is the problem in the code .
Input
3
1 2 3
Expected output
1 2 3
current output
1
#include<iostream>
#include<stdlib.h>
using namespace std;
class node //declation of node
{
public:
int data;
node *next;
node *prev;
};
node *makenode(node *head,int val) //function to create node
{
node *newnode=new node;
node *temp;
newnode->data=val;
newnode->next=0;
newnode->prev=0;
if(head==0) temp=head=newnode;
else
{
temp->next=newnode;
newnode->prev=temp;
temp=newnode;
}
return head;
}
void display(node *head) //display function
{
system("cls"); //clearing output screen
while(head!=0)
{
cout<<head->data<<" ";
head=head->next;
}
}
int main()
{
node *head;
head=0;
int val;
int s; //size of list
cout<<"ENTER THE SIZE OF LIST";
cin>>s;
system("cls");
for(int i=0;i<s;i++)
{
cout<<"ENTER THE "<<i+1<<" VALUE\n";
cin>>val;
head=makenode(head,val); //calling makenode and putting value
}
display(head); //printing value
return 0;
}
node *makenode(node *head,int val) //function to create node
{
node *newnode=new node;
node *temp; // #1
newnode->data=val;
newnode->next=0;
newnode->prev=0;
if(head==0) temp=head=newnode;
else
{
temp->next=newnode; // #2
Between the lines marked #1 and #2 above, what exactly is setting the variable temp to point to an actual node rather than pointing to some arbitrary memory address?
"Nothing", I hear you say? Well, that would be a problem :-)
In more detail, the line:
node *temp;
will set temp to point to some "random" location and, unless your list is currently empty, nothing will change that before you attempt to execute:
temp->next = newnode;
In other words, it will use a very-likely invalid pointer value and crash if you're lucky. If you're unlucky, it won't crash but will instead exhibit some strange behaviour at some point after that.
If you're not worried about the order in the list, this could be fixed by just always inserting at the head, with something like:
node *makenode(node *head, int val) {
node *newnode = new node;
newnode->data = val;
if (head == 0) { // probably should use nullptr rather than 0.
newnode->next = 0;
newnode->prev = 0;
} else {
newnode->next = head->next;
newnode->prev = 0;
}
head = newnode;
return head;
}
If you are concerned about order, you have to find out where the new node should go, based on the value, such as with:
node *makenode(node *head, int val) {
node *newnode = new node;
newnode->data = val;
// Special case for empty list, just make new list.
if (head == 0) { // probably should use nullptr rather than 0.
newnode->next = 0;
newnode->prev = 0;
head = newnode;
return head;
}
// Special case for insertion before head.
if (head->data > val) {
newnode->next = head->next;
newnode->prev = 0;
head = newnode;
return head;
}
// Otherwise find node you can insert after, and act on it.
// Checknode will end up as first node where next is greater than
// or equal to insertion value, or the last node if it's greater
// than all current items.
node *checknode = head;
while (checknode->next != 0 && (checknode->next->data < val) {
checknode = checknode->next;
}
// Then it's just a matter of adjusting three or four pointers
// to insert (three if inserting after current last element).
newnode->next = checknode->next;
newnode->prev = checknode;
if (checknode->next != 0) {
checknode->next->prev = newnode;
}
checknode->next = newnode;
return head;
}
You aren't actually linking anything together. This line: if(head==0) temp=head=newnode; is the only reason your linked list contains a value at all. The very first value sets head equal to it and when you print head you get that value. In order to properly do a linked list you need a head and tail pointer. The head points to the first element in the list and the tail points to the last. When you add an element to the end of the list you use tail to find the last element and link to it. It is easiest to make Linked List a class where you can encapsulate head and tail:
struct Node {
public:
int data;
node *next;
node *prev;
Node(int data) : data(data), next(nullptr), prev(nullptr) {} // constructor
};
class LinkedList {
private:
Node* head;
Node* tail;
public:
LinkedList() { head = tail = nullptr; }
// This function adds a node to the end of the linked list
void add(int data) {
Node* newNode = new Node(data);
if (head == nullptr) { // the list is empty
head = newNode;
tail = newNode;
}
else { // the list is not empty
tail->next = newNode; // point the last element to the new node
newNode->prev = tail; // point the new element to the prev
tail = tail->next; // point the tail to the new node
}
}
};
int main() {
LinkedList lList;
lList.add(1);
lList.add(2);
// etc...
return 0;
}

Print function isn't working properly- Linked list

I am new to the data structures and I was trying to write a code which add nodes to the beginning of the linked list. After every time user enters a new node, the program is supposed to display an updates linked list, but my program is only displaying the current entered node.
The code is as follows: -
#include<iostream.h>
#include<conio.h>
struct Node
{
int data;
Node* next;
};
struct Node* head;
void Insert(int x)
{
Node* temp=new Node();
temp->data=x;
temp->next=NULL;
head=temp;
}
void Print()
{
struct Node* temp=head;
cout<<"List is: ";
while(temp!=NULL)
{
cout<<temp->data;
temp=temp->next;
}
cout<<"\n";
}
void main()
{
head=NULL;
clrscr();
cout<<"How many numbers?\n";
int n,x,i;
cin>>n;
for(i=0; i<n; i++)
{
cout<<"Enter the number \n";
cin>>x;
Insert(x);
Print();
}
getch();
}
Your Insert method is wrong. You need to assign head to next:
void Insert(int x)
{
Node* temp=new Node();
temp->data=x;
temp->next=head;
head=temp;
}
This will then chain your list correctly.
Your Insert function is wrong. You need to use something like this in order to add new items at the end of the list:
void InsertAtTheEnd(int x) {
Node* temp = new Node();
temp->data=x;
temp->next=NULL;
if (NULL == head) {
head = temp;
} else {
Node *tmp = head;
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = temp;
}
}
And this will add them to the beggining:
void InsertAtTheBeginning(int x) {
Node* temp=new Node();
temp->data=x;
temp->next=head;
head=temp;
}
Check it out live

Deletion at end in linked lists

i am trying to write a simple program for deletion and insertion at the end of a linked list. I have managed to insert values at the end perfectly but I cannot understand what to do in deletion.
The delete function is deleteend(), display function is display() and insert function is insertend(int x) but I have problem only with delteend().
#include<iostream>
using namespace std;
struct node
{
int info;
node *next;
};
node *head = NULL;
void insertend(int x)
{
node *last = new node;
last->info = x;
last->next = NULL;
if (head == NULL)
head=last;
else
{
node *temp=head;
while(temp->next!=NULL)
temp=temp->next;
temp->next=last;
}
}
void display()
{
node *np=head;
while(np!=NULL)
{
cout<<np->info<<endl;
np=np->next;
}
}
void deleteend()
{
node *temp=head;
while(temp->next!=NULL)
temp=temp->next;
delete temp;
}
int main()
{
int data;
char ch;
do
{
cout<<"Enter value:";cin>>data;
cout<<endl;
insertend(data);
cout<<"Enter more values?(y/n):";cin>>ch;
cout<<endl;
} while(ch=='y');
cout<<"Your list is"<<endl;
display();
do
{
cout<<"Delete value from end?(y/n):";cin>>ch;
cout<<endl;
if(ch=='y')
deleteend();
} while(ch=='y');
cout<<"Your list is"<<endl;
display();
return 0;
}
You need to maintain a reference to the node before the node you want to delete, so that you can set the pointers correctly.
Since you are only supporting delete from end, your function should look more like this:
void deleteend()
{
// in case we have an empty list to begin with
if (!head) {
return;
}
if (head->next == NULL) {
// our list was one element, so delete head and set our list to null
delete head;
head = NULL;
return;
}
// here, have a node that points to the head
// and then have a node pointer to the next element
// Traverse the list until you hit the end
node *prev = head;
node *end = head->next;
while (end->next != NULL) {
prev = end;
end = end->next;
}
// once we're here, prev should be the second to last element
// and end is the last element
// so delete end and set prev->next to NULL
delete end;
prev->next = NULL;
}
This code can be adapted to delete any arbitrary node from the middle of the list.
For deleteend(), you need to set what is the next to last nodes next pointer to null. This can be done using two pointers, one for the current node and one for the previous node, or by using a pointer to pointer. If using two pointers, in the case of a list with a single node, then there is no previous node, only the head pointer. biryee's answer shows the two pointer method.
Example code for pointer to pointer:
void deleteend()
{
node **ppnode = &head; // ptr to head or a node's next pointer
if(head == NULL)
return;
// advance ppnode so *ppnode points to last node in list
while((*ppnode)->next != NULL)
ppnode = &(*ppnode)->next;
delete(*ppnode); // delete last node
*ppnode = NULL; // set what was pointer to last node to NULL
}

Why can't I insert nodes after head into a C++ linked list?

Could someone please help me identify the problem with the code below.
#include <iostream>
using namespace std;
struct node
{
int a,b;
struct node* next=NULL;
};
node* head=NULL;
void insert(int a,int b)
{
if(head==NULL)
{
head=new node;
head->a=a;
head->b=b;
return;
}
node* cur=head;
while(cur!=NULL)
{
cur=cur->next;
}
cur=new node;
cur->a=a;
cur->b=b;
return;
}
void display()
{
node* cur=head;
while(cur!=NULL)
{
cout<<cur->a<<"\t"<<cur->b<<"\n";
cur=cur->next;
}
}
int main()
{
int i;
for(i=0;i<3;++i)
{
insert(i,i+1);
}
display();
//cout<<h->next->a;
return 0;
}
This is the output that I get:
0 1
It seems that I can only display the head node and none after gets inserted. If I try to access the next node after head, I get a segmentation fault. Why is that?
Your search code is:
node* cur=head;
while(cur!=NULL)
{
cur=cur->next;
}
cur=new node;
At the end of the loop, you've found the right place to add the new node, but you overwrite that with cur = new node; — so you need to use something more like:
node *new_node = new node;
new_node->a = a;
new_node->b = b;
new_node->next = nullptr;
cur->next = new_node;
Or, equivalently:
cur->next = new node;
cur->next->a = a;
cur->next->b = b;
cur->next->next = nullptr;
Even better, you'd create a constructor for the struct node class, such as:
node(int a_init = 0, int b_init = 0) : a(a_init), b(b_init), next(nullptr) { }
and then:
cur->next = new node(a, b);
would do the whole initialization job.
While inserting, update head->next to NULL (when head is NULL)
and curr->next to NULL (when some elements are already in the list)
respectively.
You are not linking head to curr. To link head and curr, you can
create another pointer instead to hold the new element, say new_ptr.
Keep curr such that curr->next=NULL, and then write
curr->next=new_ptr.
void insert(int a,int b)
{
if(head==NULL)
{
head=new node;
head->a=a;
head->b=b;
head->next=NULL;
return;
}
node* cur=head,*new_ptr;
while(cur->next!=NULL)
{
cur=cur->next;
}
new_ptr=new node;
new_ptr->a=a;
new_ptr->b=b;
new_ptr->next=NULL;
curr->next=new_ptr;
return;
}
I found out the bug .While inserting , instead of sitting in a node and checking if it is null , look 1 node ahead and check if its null. Because if you don't , then the list will get broken and cpp allocates memory else where rather than to the pointer of the last list node's next branch.
Modified insert function :
void insert(int a,int b)
{
if(head==NULL)
{
head=new node;
head->a=a;
head->b=b;
head->next=NULL;
return;
}
node* cur=head;
while(cur->next!=NULL)
{
//cout<<cur->a<<"\t"<<cur->b<<"\n";;
cur=cur->next;
}
cur->next=new node;
cur->next->a=a;
cur->next->b=b;
return;
}
At the time of creation of any node , the next pointer of that node becomes null as per the definition of your node.
struct node
{
int a,b;
struct node* next=NULL;
};
Now,after the creation of start node ,the next pointer of start node is NULL.And when u created your second node ,you didn't point the next node of your first node to the second node.Then how will you be able to reach to the second node if you do not have the pointer to the second node.
So the solution will be --
void insert(int a,int b)
{
node *temp;
if(head==NULL)
{
head=new node;
head->a=a;
head->b=b;
temp=head;
return;
}
node* cur=head;
while(cur!=NULL)
{
cur=cur->next;
}
cur=new node;
temp->next=cur;
cur->a=a;
cur->b=b;
temp=cur;
return;
}