一、指针版
1 struct Node { 2 int value; 3 Node *next; 4 }; 5 int chaxun(Node* head, int k) { 6 Node* p = head; 7 for (int i = 1; i < k; ++ i) { 8 p = p->next; 9 } 10 return p->value; 11 } 12 void charu(Node* head, int k, int value) { 13 Node* p = head; 14 for (int i = 1; i < k; ++ i) { 15 p = p->next; 16 } 17 Node* q = new Node; 18 q->value = value; 19 q->next = p->next; 20 p->next = q; 21 } 22 void shanchu(Node* head, int k) { 23 Node* p = head; 24 for (int i = 2; i < k; ++ i) { 25 p = p->next; 26 } 27 p->next = p->next->next; 28 }
二、数组版
1 struct Node { 2 int value; 3 Node *next; 4 }; 5 int chaxun(Node* head, int k) { 6 Node* p = head; 7 for (int i = 1; i < k; ++ i) { 8 p = p->next; 9 } 10 return p->value; 11 } 12 void charu(Node* head, int k, int value) { 13 Node* p = head; 14 for (int i = 1; i < k; ++ i) { 15 p = p->next; 16 } 17 Node* q = new Node; 18 q->value = value; 19 q->next = p->next; 20 p->next = q; 21 } 22 void shanchu(Node* head, int k) { 23 Node* p = head; 24 for (int i = 2; i < k; ++ i) { 25 p = p->next; 26 } 27 p->next = p->next->next; 28 } 29 //数组版 30 int value[maxn], next[maxn], tot; 31 int chaxun(int head, int k) { 32 int p = head; 33 for (int i = 1; i < k; ++ i) { 34 p = next[p]; 35 } 36 return value[p]; 37 }//k前一个的next指向value[k] 38 void charu(int head, int k, int val) { 39 int p = head; 40 for (int i = 1; i < k; ++ i) { 41 p = next[p]; 42 } 43 int q = tot ++;//tot链表元素总数量 44 value[q] = val; 45 next[q] = next[p]; 46 next[p] = q; 47 } 48 void shanchu(int head, int k) { 49 int p = head; 50 for (int i = 2; i < k; ++ i) 51 { 52 p = next[p]; 53 } 54 next[p] = next[next[p]];//要删除的元素前一个的next直接指向要删除下一个元素 55 }