链表

 1 #include "node.h"
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 
 5 typedef struct _node {
 6     int value;
 7     struct _node *next;
 8 } Node;
 9 
10 typedef struct _list {    //好处: 用一个自己定义的数据结构代表链表 
11     Node* head;
12     //Node* tail;
13 } List;
14 void add (List* pList, int number);
15 void print(List *pList);
16 
17 int main(int argc, char const *argv[])
18 {
19     List list;
20     Node * head = NULL;
21     int number;
22     list.head = NULL;
23     //list.tail = NULL;
24     do {
25         scanf("%d",&number);
26         if (number != -1){    //得到一个number之后制造链表的一个结点 
27             add(&list, number);
28         }
29     } while (number != -1);
30     print(&list);
31     scanf("%d",&number);    //寻找元素并删除 
32     Node *p;
33     int isFound = 0;
34     for ( p=list.head; p; p=p->next){
35         if ( p->value == number ){
36             printf("找到了
");
37             isFound = 1;
38             break; 
39         }
40     }
41     if ( isFound == 0){
42         printf("没找到
");
43     }
44     Node *q; 
45     for ( q=NULL, p=list.head; p; q=p, p=p->next){    //链表的删除 
46         if ( p->value == number ){
47             if ( q ){    //如果q存在 
48                 q->next = p->next;
49             }
50             else {
51                 list.head = p->next;
52             } 
53             free(p);
54             break; 
55         }
56     }
57     for ( p=head; p; p=q){    //链表的清除 
58         q = p->next;
59         free(p);
60     }
61     
62     return 0;
63 }
64 
65 void add (List* pList, int number){
66     // add to linked-list
67     Node *p = (Node*)malloc(sizeof(Node));
68     p->value = number;
69     p->next = NULL;
70     // find the last
71     Node *last = pList->head;
72     if ( last ){    //如果last不是NULL的话 
73         while ( last->next ){    //next 有东西, 就让last指向下一位 
74             last = last->next;
75             }
76     // attach 
77     last->next = p;
78     } 
79     else {
80         pList->head = p;
81     }
82 }
83 
84 void print(List *pList) {
85     Node *p;
86     for ( p=pList->head; p; p = p->next){
87         printf("%d	", p->value);
88     }
89     printf("
");
90 }

用画图的方式来了解链表是一个不错的选择, 可能是对指针方面的知识还不理解, 链表当中用到的指针的应用需要看一段时间才可以适应并且理解其作用;

要深入了解链表的话可能先要做PTA的题目, 通过题目来了解链表的功能, 熟练的创建链表, 搜索链表的元素, 也是一个很耗费时间的学习;

重新回去看指针的知识, 希望能加深一步了解, 让链表不那么吃力;

原文地址:https://www.cnblogs.com/zhengxin909/p/11992812.html