Sunday, June 3, 2012

Deletion of last node from a linked list


To delete the last node of a linked list traverse through the linked list using two moving structure type pointer. Keep one pointer one step ahead of the second pointer, so that when one pointer reaches the last node of linked list the other will be on the last but one. Free the last node of linked list and necessary connections of pointers needed.

# include < stdio.h>
# include < stdlib.h>
struct link
{
char data;
struct link *next;
};

int i,number;
char ab;
struct link *p,*node;
void create(struct link *n)
{
char ch;
i=1;
node=n;
printf("\n Enter single character for node: %d: ",i);
node->data=getche();
node->next = NULL;
printf("\n Enter choice--'n' for break: ");
ch = getche();
while(ch != 'n')
{
i=i+1;
node->next = (struct link* ) malloc(sizeof(struct link));
node = node->next;
printf("\n Enter single character for node: %d: ",i);
node->data=getche();
node->next = NULL;
printf("\n Enter choice-- 'n' for break: ");
ch = getche();
}
printf("\n Total nodes = %d\n", i);
}
void dis(struct link *n)
{
node=n;
if(node==NULL)
{
printf("\nNo elements in the list.");
return;
}
while(node)
{
printf("%c\n",node->data);
node=node->next;
}
}
struct link *del(struct link *n)
{
node=n->next;
p = n;
if (node == NULL)
{
n=node;
free(p);
}
else
{
while(node->next)
{
node = node->next;
p = p->next;
}
p->next = node->next;
free(node);
}
return n;
}
void main()
{
struct link *start = (struct link *) malloc(sizeof(struct link));
clrscr();
create(start);
printf("\nThe linked list as created ......\n");
dis(start);
start=del(start);
printf("\nNow the list is as follows ......\n");
dis(start);
getch();
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner