作业 - 链表打印

main.m

 1 #import <Foundation/Foundation.h>
 2 
 3 typedef struct Node_{                    // 别名: Node
 4     int value;
 5     struct Node_ *next;
 6 }Node;
 7 
 8 Node *creatNode(int value, Node *next){  // 函数: 创建单个链节
 9     Node *node = malloc(sizeof(Node));
10     node -> value = value;
11     node -> next = NULL;
12     return node;
13 }
14 
15 void printlist(Node *head){             // 函数: 打印整个链表
16     for(Node *node = head;node != NULL; node = node->next){
17         printf("%d\n",node -> value);
18     }
19 }
20 
21 void reverselist(Node *head){           // 函数: 反转链表并打印
22     
23     printf("reversed:\n");
24     
25     if (head -> next == NULL) {         // 如果是单链节的链表就不用反转
26         return;
27     }
28     
29     Node *a;
30     Node *b;
31     Node *c;
32     
33     a = head;
34     b = head -> next;
35     head -> next = NULL;
36     c = b -> next;
37     
38     while (c) {
39         b -> next = a;
40         a = b;
41         b = c;
42         c = c -> next;
43     }
44     
45     b -> next = a;                      // 处理剩余的最后一个链节
46     printlist(b);                       // 此时链节起点是 b
47 }
48 
49 int main(int argc, const char * argv[]) {
50     @autoreleasepool {
51 
52         Node *current = creatNode(0, NULL);
53         Node *head    = current;        // 创建起始端点
54         
55         for (int i=1; i<=9 ; i++) {     // 创建余下链节
56             current -> next = creatNode(i, NULL);
57             current = current->next;
58         }
59         
60         printlist(head);                // 调用打印函数
61         reverselist(head);              // 调用反转并打印函数
62     }
63     return 0;
64 }

 

posted @ 2016-05-09 12:31  小样和牛牛  阅读(298)  评论(0编辑  收藏  举报