Sunday, June 13, 2010

Mth from the last of Link List in C

1: #include <stdio.h>
2: 
3: typedef struct node
4: {
5:   struct node *next;
6:   int data;
7: }listNode;
8: 
9: //passing the **head so that head can be modified
10: int insert(listNode **head,listNode *node)
11: {
12:   if(*head == NULL)
13:     *head = node;
14:   else
15:   {
16:     node->next = *head;
17:     *head = node;
18:   }    
19:   return 1;
20: }
21: 

22: int show(listNode *head)
23: {
24:   listNode *temp = head;
25:   printf("Head");
26:   while(temp)
27:   {
28:     printf("->%d",temp->data);
29:     temp = temp->next;
30:   }
31:   printf("->NULL\n");
32: }
33: 
34: //will use two pointers, one at head
35: //and other at the mth element from head
36: //then move both at the same time
37: //until the end of list
38: int mthToTheLast(listNode *head, int mth)
39: {
40:   listNode *current = head;
41:   listNode *mThFromHead = head;
42:   
43:   //move the mThFromHead to mth position
44:   while(--mth >= 0 )
45:   {
46:     mThFromHead = mThFromHead->next;
47:     if(mThFromHead == NULL)
48:       return -1;
49:   }
50:   
51:   //now move both ptr at same time
52:   while(mThFromHead->next != NULL)
53:   {
54:     current = current->next;
55:     mThFromHead = mThFromHead->next;
56:   }
57:   
58:   return current->data;
59: }
60: 
61: int main(int argc, char **argv)
62: {
63:   listNode *head = NULL;
64:   int i = 0;
65:   for(;i < 3; i++)
66:   {
67:     listNode *node = (listNode*)malloc(sizeof(listNode));
68:     node->data = rand();
69:     node->next = NULL;
70:     insert(&head,node);
71:   }
72:   //show(head);
73:   
74:   printf("0th from the last %d\n",mthToTheLast(head,0));
75:   printf("1th from the last %d\n",mthToTheLast(head,1));
76:   printf("2th from the last %d\n",mthToTheLast(head,2));
77:   printf("3th from the last %d\n",mthToTheLast(head,3));
78:   printf("hello world\n");
79:   getchar();
80:   
81:   return 0;
82: }
83: 

No comments: