1. 程式人生 > 實用技巧 >LeetCode——K個一組翻轉連結串列

LeetCode——K個一組翻轉連結串列

題目地址:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/

解題思路:增加頭結點,通過頭結點來實現倒序。

class Solution {
 public:
     ListNode* reverseKGroup(ListNode* head, int k) {
         ListNode* p ,*t,*head_;
         ListNode* q = head;
         ListNode *Head= new ListNode(-1);//增加Head頭結點
         Head->next = head;
         
int i, num = 0,flag=0; p = Head; while (p->next) { num++; p = p->next; } Head->next = NULL; p = Head->next; head_ = Head; for (i = 1; i <= num && num / k != flag; i++) { t = q; q
= q->next; head_->next = t; t->next = p; p = t; if (i%k == 0) { while (head_->next) { head_ = head_->next; } head_->next = NULL; p = head_->next; flag
++; } } if (i != num + 1) head_->next = q; head = Head->next; return head; } };