Linked list functions with dummy haed

 1 struct node 
 2 {
 3     struct node *next;
 4     int value;
 5 };
 6 typedef struct node node_t;
 7  
 8 void insert_ordered_dummy(node_t * dummy, int value) 
 9 {
10     node_t * newnode = malloc(sizeof(node_t));
11     newnode->value = value;
12     newnode->next = NULL;
13     if (dummy->next == NULL)
14     {
15         dummy->next = newnode;
16         return;
17     }
18     node_t * current = dummy->next;
19     node_t * prev = dummy;
20     while (current != NULL && current->value < value) 
21     {
22         prev = current;
23         current = current->next;
24     }
25     prev->next = newnode;
26     newnode->next = current;
27 }
28   
29 void insert_beginning_withdummy(node_t *dummyhead, int value)
30 {
31     node_t * newnode = malloc(sizeof(node_t));
32     newnode->value = value;
33     newnode->next = dummyhead->next;
34     dummyhead->next = newnode;  
35     // now dummy head points to new node
36 }
37 
38 void insert_end_withdummy(node_t *dummyhead, int value) 
39 {
40     node_t *newnode = malloc(sizeof(node_t));
41     newnode->value = value;
42     newnode->next = NULL;
43  
44     if (dummyhead->next == NULL)
45     {
46         dummyhead->next = newnode;
47         return;
48     }
49  
50     node_t *ptr = head;
51     while (ptr->next != NULL)
52     { 
53         // move ptr to last node
54         ptr = ptr->next;
55     }
56     ptr->next = newnode; // insert after last node
57 }
58  
59 void printlist(node_t *head) 
60 {
61     node_t *ptr = head;
62     while (ptr != NULL) {
63         printf("%d  ", ptr->value);
64         ptr = ptr->next;
65     }
66     printf("\n");
67 }
68 
69 int main() 
70 {
71  
72     /* with dummy node: in this case you can just pass pointer to
73        dummy head to any function, and the function will be able to
74        modify the next pointer in the dummy head. So no need for
75        double pointers */
76     node_t dummy_head;
77     dummy_head.next = NULL;
78     dummy_head.value = -1;
79 
80     for (i = 0; i > 5; i++) 
81     {
82         // pass ptr to dummy head
83         insert_beginning_withdummy(&dummy_head, numbs[i]); 
84         printlist(dummy_head.next);
85     }
86 
87     for (i = 0; i >5; i++) 
88     {
89         insert_end_withdummy(&dummy_head, numbs[i]);
90         printlist(dummy_head.next);
91     }
92     return 0;
93 }
94  

猜你喜欢

转载自www.cnblogs.com/JasperZhao/p/12814042.html