码迷,mamicode.com
首页 > 其他好文 > 详细

链表的插入、删除

时间:2015-04-15 22:46:49      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

结构体:

 

1 typedef struct Student{
2     int m_val;
3     struct Student* m_next;
4 }NODE,*pNODE;

 

 

 

链表的插入:

 1 //尾部插入
 2 void linkInitTail(pNODE* pphead)
 3 {
 4     int val;
 5     pNODE pNew,pTail;
 6     while(scanf("%d",&val) == 1)
 7     {
 8         pNew = (pNODE)calloc(1,sizeof(NODE));
 9         pNew->m_val = val;
10         if(*pphead == NULL)
11         {
12             *pphead = pNew;
13             pTail = pNew;
14         }
15         else
16         {
17             pTail->m_next = pNew;
18             pTail = pNew;
19         }
20     }
21     pTail = NULL;
22 }
23 
24 //头部插入,不需记录尾部结点
25 void linkInitHead(pNODE* pphead)
26 {
27     pNODE pNew;
28     int val;
29     while(scanf("%d",&val) == 1)
30     {
31         pNew = (pNODE)calloc(1,sizeof(NODE));
32         pNew->m_val = val;
33         pNew->m_next = *pphead;
34         *pphead = pNew;
35     }
36 }
37 //有序插入
38 void linkInitOrder(pNODE* pphead)
39 {
40     pNODE pNew,pPrevious,pCurrent;
41     int val;
42     while(scanf("%d",&val) == 1)
43     {
44         pNew = (pNODE)calloc(1,sizeof(NODE));
45         pNew->m_val = val;
46 
47         pCurrent = *pphead;
48         pPrevious = NULL;
49 
50         while(pCurrent && pCurrent->m_val < pNew->m_val)
51         {
52             pPrevious = pCurrent;
53             pCurrent = pCurrent->m_next;
54         }
55         if(pPrevious == NULL)
56         {
57             pNew->m_next = *pphead;
58             *pphead = pNew;
59         }
60         else
61         {
62             pNew->m_next = pCurrent;
63             pPrevious->m_next = pNew;
64         }
65     }
66 }

 

链表的删除:

 1 void linkDelete(pNODE* pphead, int value)
 2 {
 3     pNODE pPrevious = NULL, pCurrent = *pphead;
 4     while(pCurrent && pCurrent->m_val != value)
 5     {
 6         pPrevious = pCurrent;
 7         pCurrent = pCurrent->m_next;
 8     }
 9     if(pCurrent == NULL)
10         printf("Not exist!");
11     else
12     {
13         if(pPrevious == NULL)//删去头结点
14         {
15             *pphead = pCurrent->m_next;
16             free(pCurrent);
17         }
18         else
19         {
20             pPrevious->m_next = pCurrent->m_next;
21             free(pCurrent);
22         }
23     }
24 
25 }

 

链表的插入、删除

标签:

原文地址:http://www.cnblogs.com/cpsmile/p/4430266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!