Friday 6 February 2015

Create a Single Linked List program using C

#include struct Node { int data; struct Node *next; }; struct Node *create_list(int *ptr,int n) { struct Node *hptr=NULL,*tptr,*temp; int i; if(n>0) { hptr=(struct Node*)malloc(sizeof(struct Node)); tptr=hptr; hptr->data=ptr[0]; for (i=1;idata=ptr[i]; temp->next=NULL; tptr->next=temp; tptr=temp; } } return hptr; } void display(struct Node *dptr) { struct Node *temp; for (temp=dptr;temp!=NULL ;temp=temp->next ) { printf("%d\n",temp->data); } } struct Node *getNfromLast(struct Node *hptr,int n) { struct Node *fptr,*bptr; int i; fptr=hptr; bptr=hptr; for (i=0;inext; while(fptr->next!=NULL) { fptr=fptr->next; bptr=bptr->next; } return bptr; } void main() { int arr[]={1,2,3,4,5,6}; struct Node *hptr,*tptr; hptr=create_list(arr,6); display(hptr); tptr=getNfromLast(hptr,3); printf("\n%d\n",tptr->data); }

No comments:

Post a Comment