【题目】
给定一个单链表的头节点head,实现一个调整单链表的函数,使得每K个节点之间逆序,如果最后不够K个节点一组,则不调整最后几个节点。
例如:
链表:1->2->3->4->5->6->7->8->null,K = 3。
调整后为:3->2->1->6->5->4->7->8->null。其中7、8不调整,因为不够一组。
【解题思路】
方法一:
使用栈,每K个节点依次入栈,并依次删除
然后栈弹出尾插法插入节点
方法二:
直接在链表中使用头插法,进行反转
1 #include <iostream> 2 #include <stack> 3 using namespace std; 4 5 struct Node 6 { 7 int val; 8 Node* next; 9 Node(int a = 0) :val(a), next(nullptr) {} 10 }; 11 void printList(Node* head) 12 { 13 Node *p = head->next; 14 while (p) 15 { 16 cout << p->val << "->"; 17 p = p->next; 18 } 19 cout << endl; 20 } 21 22 void byStack(Node* head, int k) 23 { 24 Node* p = head->next, *pre = head; 25 stack<Node*>s;//保留节点地址,就不用删除和新建节点步骤 26 while (p) 27 { 28 s.push(p); 29 p = p->next; 30 if (s.size() == k) 31 { 32 pre->next = p; 33 while (!s.empty()) 34 { 35 s.top()->next = pre->next;//断开循环 36 pre->next = s.top(); 37 pre = pre->next; 38 s.pop(); 39 } 40 } 41 } 42 printList(head); 43 } 44 45 void notStack(Node* head, int k) 46 { 47 Node* p = head->next, *pre = head, *q, *tmp = nullptr; 48 int s = 0; 49 while (p) 50 { 51 if (s == 0) 52 { 53 tmp = pre->next;//每次循环更新的头结点 54 pre->next = nullptr;//断开循环 55 } 56 q = p->next; 57 p->next = pre->next; 58 pre->next = p; 59 p = q; 60 s++; 61 if (s == k) 62 { 63 s = 0; 64 pre = tmp; 65 pre->next = p; 66 } 67 } 68 tmp->next = nullptr; 69 p = pre->next; 70 pre->next = nullptr;//断开循环 71 while (p)//将后面不足k个节点还原 72 { 73 q = p->next; 74 p->next = pre->next; 75 pre->next = p; 76 p = q; 77 } 78 printList(head); 79 } 80 81 int main() 82 { 83 Node *head = new Node(-1); 84 Node* p = head; 85 for (int i = 1; i <= 8; ++i) 86 { 87 Node*q = new Node(i); 88 p->next = q; 89 p = q; 90 } 91 printList(head); 92 //byStack(head, 3); 93 notStack(head, 3); 94 return 0; 95 }