1. 程式人生 > >資料結構-線性表的鏈式表示-C(建立,插入,刪除,合併)

資料結構-線性表的鏈式表示-C(建立,插入,刪除,合併)

臨近期末,不得不復習的當代大學生╮(╯▽╰)╭。本來這一個隨筆應該和上一個是放在一起的,但昨天太困了就沒寫這個,所以就分兩個發好了。話不多說,程式碼參上。

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 typedef struct LNode {
  4     int data;
  5     struct LNode *next;
  6 }LNode,*LinkList;
  7 //頭插法
  8 void CreateList(LinkList &L, int n) {
  9     L = (LinkList)malloc(sizeof
(LNode)); 10 if (!L) { 11 printf("空間分配失敗\n"); 12 } 13 L->next = NULL; 14 printf("輸入%d個數\n", n); 15 for (int i = 0; i < n; i++) { 16 LinkList p; 17 p = (LinkList)malloc(sizeof(LNode)); 18 scanf_s("%d", &p->data); 19 p->next = L->next;
20 L->next = p; 21 } 22 } 23 //尾插法 24 void CreateListend(LinkList &L, int n) { 25 L = (LinkList)malloc(sizeof(LNode)); 26 L->next = NULL; 27 LinkList r, s; 28 r = (LinkList)malloc(sizeof(LNode)); 29 if (!L) { 30 printf("空間分配失敗\n"); 31 } 32
r = L; 33 printf("輸入%d個數\n", n); 34 for (int i = 0; i < n; i++) { 35 s = (LinkList)malloc(sizeof(LNode)); 36 scanf_s("%d", &s->data); 37 s->next = r->next; 38 r->next = s; 39 r = s; 40 } 41 } 42 //遍歷 43 void Travellist(LinkList &L) { 44 LinkList s; 45 s = L->next; 46 while (s != NULL) { 47 printf("%d", s->data); 48 s = s->next; 49 } 50 printf("\n"); 51 } 52 //插入 53 int Insertlist(LinkList &L, int i,int e) { 54 LinkList p; 55 p = L; 56 int j = 0; 57 while (p && j < i - 1) { 58 p = p->next; 59 j++; 60 } 61 if (j >= i - 1 || !p) { 62 printf("插入失敗\n"); 63 return 0; 64 } 65 LinkList s; 66 s = (LinkList)malloc(sizeof(LNode)); 67 s->data = e; 68 s->next = p->next; 69 p->next = s; 70 } 71 //刪除 72 void Deletelist(LinkList &L) { 73 LinkList p; 74 p = L->next; 75 int flag = 0; 76 int e; 77 LinkList r; 78 r = (LinkList)malloc(sizeof(LNode)); 79 printf("請輸入要刪除的數\n"); 80 scanf_s("%d", &e); 81 while (p) { 82 if (p->data == e) { 83 flag = 1; 84 break; 85 } 86 r = p; 87 p = p->next; 88 } 89 if (flag == 0) { 90 printf("查詢失敗\n"); 91 } 92 else { 93 r->next = p->next; 94 free(p); 95 } 96 } 97 //合併 98 void MergeList(LinkList &La, LinkList &Lb, LinkList &Lc) { 99 LinkList pa, pb, pc; 100 Lc = (LinkList)malloc(sizeof(LNode)); 101 pa = (LinkList)malloc(sizeof(LNode)); 102 pb= (LinkList)malloc(sizeof(LNode)); 103 pc= (LinkList)malloc(sizeof(LNode)); 104 pa = La->next; 105 pb = Lb->next; 106 Lc = pc = La; 107 while (pa && pb) { 108 if (pa->data < pb->data) { 109 pc->next = pa; 110 pc = pa; 111 pa = pa->next; 112 } 113 else if (pa->data > pb->data) { 114 pc->next = pb; 115 pc = pb; 116 pb = pb->next; 117 } 118 else if (pa->data == pb->data) { 119 pc->next=pa; 120 pc = pa; 121 pa = pa->next; 122 pb = pb->next; 123 } 124 } 125 if (pa) { 126 pc->next = pa; 127 } 128 else { 129 pc->next = pb; 130 } 131 free(Lb); 132 } 133 int main() { 134 LinkList L1; 135 LinkList L2; 136 LinkList L3; 137 CreateListend(L1, 3); 138 CreateListend(L2, 3); 139 MergeList(L1, L2, L3); 140 Travellist(L3); 141 return 0; 142 }

希望期末可以過關= =