标签:
1 #include <iostream> 2 #include "stdio.h" 3 #include "stdlib.h" 4 #include "cstring" 5 using namespace std; 6 7 #define N 10 8 //创建节点 9 typedef struct Node{ 10 11 char name[20]; 12 int age; 13 struct Node* link; 14 }Student; 15 16 Student* createList(int n) 17 { 18 Student* head = NULL; //头节点 19 Student* pNode = NULL; //动态节点 20 Student* sNode = NULL; //每次创建新的节点 21 if ((head = (Student*)malloc(sizeof(Student))) == NULL) 22 { 23 printf("Fail...\n"); 24 return NULL; 25 } 26 //头节点初始化 27 strcpy(head->name, "HeadNode"); 28 head->age = 25; 29 head->link = NULL; 30 //动态节点指向头节点: 31 pNode = head; 32 for (int i=0; i < n-1; ++i) 33 { 34 if ((sNode = (Student*)malloc(sizeof(Student))) == NULL) 35 { 36 printf("Fail...\n"); 37 return NULL; 38 } 39 //节点指针指向下一个节点 40 pNode->link = sNode; 41 cout << "Name:" ; 42 cin >> sNode->name; 43 cout << "Age:"; 44 cin >> sNode->age; 45 sNode->link = NULL; 46 pNode =sNode; 47 } 48 return head; 49 } 50 //链表打印 51 void showNode(Student* head) 52 { 53 Student* pNode; 54 pNode = head; 55 while (pNode != NULL) { 56 cout << "*******************************\n"; 57 cout << "Name:" << pNode->name; 58 cout << " Age:" << pNode->age; 59 cout << "\n"; 60 pNode = pNode->link; 61 } 62 } 63 //链表回收 64 void freeList(Student* h){ 65 66 while (h != NULL) 67 { 68 Student* p; 69 h = h->link; 70 free(p); 71 p = h; 72 } 73 74 } 75 76 //插入节点 77 void insertNode(Student* pNode) 78 { 79 Student* sNode = (Student*)malloc(sizeof(Student)); 80 cout << "please input the insertNode information\n"; 81 cout << "Name:" ; 82 cin >> sNode->name; 83 cout << "Age:"; 84 cin >> sNode->age; 85 sNode->link = pNode->link; 86 pNode->link = sNode; 87 } 88 //查询节点 89 Student* searchNode(Student* head, char* name) 90 { 91 Student* pNode = head; 92 while (pNode != NULL) { 93 if (strcmp(pNode->name, name) == 0) { 94 return pNode; 95 } 96 pNode = pNode->link; 97 } 98 return pNode; 99 } 100 101 Student* deleteNode(Student* head, char* name) 102 { 103 if (head == NULL) { 104 return NULL; 105 } 106 Student* p1 = head; 107 Student* p2 = head->link; 108 109 //判断删除的是否是头节点 110 if (strcmp(p1->name, name) == 0) { 111 head = head->link; 112 free(p1); 113 return head; 114 } 115 116 //判断删除后面的节点 117 while ( p2 != NULL) 118 { 119 if (strcmp(p2->name, name) == 0) 120 { 121 p1->link = p2->link; 122 free(p2); 123 return head; 124 } 125 p1 = p2; 126 p2 = p2->link; 127 } 128 return head; 129 } 130 131 int main(int argc, const char * argv[]) 132 { 133 Student* head = createList(4); 134 Student* sNode = searchNode(head, "b"); 135 insertNode(sNode); 136 showNode(head); 137 deleteNode(head,"b"); 138 cout<< "\n删除名字为b的节点后链表为:\n"; 139 showNode(head); 140 freeList(head); 141 return 0; 142 }
标签:
原文地址:http://www.cnblogs.com/cai1432452416/p/5262831.html