标签:
这两天都在学习数据结构中的链表操作,觉得有很多东西想跟大家分享,通常写链表一般会创建一个带头结点的链表,带头结点链表非常容易的进行链表的遍历,而不带头结点的链表,一马虎就会指错,所以在这里跟大家分享下我进行没有头结点的创建时的心得!
1、创建无头结点链表(头插)
2、删除中间节点(不是第一个也不是最后一个)
1 #include<stdio.h> 2 #include<malloc.h> 3 typedef char ElemType; 4 typedef struct node 5 { 6 ElemType data; 7 struct node *next; 8 }NHLink; 9 10 //创建单链表 头插 11 void Create(NHLink **nhead) 12 { 13 ElemType x; 14 while (1) 15 { 16 scanf_s("%c", &x); 17 if (x != ‘*‘) 18 { 19 NHLink *p = (NHLink *)malloc(sizeof(ElemType)*sizeof(NHLink)); 20 p->data = x; 21 p->next = NULL; 22 if (*nhead == NULL) 23 { 24 *nhead = p; 25 } 26 else 27 { 28 //头插 29 p->next = *nhead; 30 *nhead = p; 31 } 32 } 33 else 34 { 35 break; 36 } 37 } 38 } 39 //查找 按值查找 40 int Search(NHLink **nhead, ElemType x) 41 { 42 NHLink *p = *nhead; 43 int index = 1; 44 while (p) 45 { 46 if (p->data == x) 47 { 48 return index; 49 } 50 p = p->next; 51 index++; 52 } 53 return 0; 54 } 55 //按下标查找 56 NHLink *Find(NHLink **nhead, int index) 57 { 58 if (index <= 0) 59 { 60 return NULL; 61 } 62 NHLink *p = *nhead; 63 int i = 1; 64 while (p && i != index) 65 { 66 p = p->next; 67 i++; 68 } 69 while (p != NULL) 70 { 71 return p; 72 } 73 } 74 //(2)删除中间节点(不是第一个也不是最后一个) 75 void Delete(NHLink **nhead, NHLink *p) 76 { 77 NHLink *pNext = p->next; 78 if (p->next != NULL) 79 { 80 p->next = pNext->next; 81 p->data = pNext->data; 82 delete pNext; 83 pNext = NULL; 84 } 85 else //删除为尾节点时,就需要从头遍历链表 86 { 87 pNext = (*nhead)->next; 88 while ((pNext->next != NULL) && (pNext->next != p)) 89 { 90 pNext = pNext->next; 91 } 92 if (pNext->next != NULL) 93 { 94 pNext->next = pNext->next->next; 95 delete p; 96 p = NULL; 97 } 98 } 99 } 100 //插入 尾插 101 void InsertTail(NHLink **head, ElemType x) 102 { 103 NHLink *p = (NHLink *)malloc(sizeof(ElemType)*sizeof(NHLink)); 104 p->data = x; 105 p->next = NULL; 106 if (*head == NULL) 107 { 108 *head = p; 109 } 110 else 111 { 112 while ((*head)->next) 113 { 114 *head = (*head)->next; 115 } 116 (*head)->next = p; 117 } 118 } 119 //插入 头插 120 void InsertHead(NHLink **head, ElemType x) 121 { 122 NHLink *p = (NHLink *)malloc(sizeof(ElemType)*sizeof(NHLink)); 123 p->data = x; 124 p->next = NULL; 125 p->next = *head; 126 *head = p; 127 } 128 void Show(NHLink *nhead) 129 { 130 NHLink *p = nhead; 131 while (p) 132 { 133 printf("%c ", p->data); 134 p = p->next; 135 } 136 printf("\n"); 137 } 138 int main() 139 { 140 NHLink *nhead = NULL; 141 Create(&nhead); 142 Show(nhead); 143 //按值查找 144 int index = Search(&nhead, ‘c‘); 145 if (index == 0) 146 { 147 printf("未找到该节点!\n"); 148 } 149 else 150 printf("%d\n", index); 151 152 //按下标查找 153 NHLink *p = Find(&nhead, 4); 154 if (p == NULL) 155 printf("查找范围不合法!\n"); 156 else 157 printf("%c\n", p->data); 158 //(2)删除某一节点 159 Delete(&nhead, p); 160 Show(nhead); 161 //插入 162 InsertTail(&nhead,‘x‘); 163 Show(nhead); 164 return 0; 165 }
标签:
原文地址:http://www.cnblogs.com/xianwwc/p/5426704.html