[LeetCode]—Reverse Nodes in k-Group 将链表以n个节点为一组进行逆序

来源:互联网 发布:淘宝搜相似图片搜索 编辑:程序博客网 时间:2024/05/07 18:07

Reverse Nodes in k-Group

 

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

注意:如果最后不足长度为K的部分,不进行逆序。

分析:其实本题主要在考察链表逆序的问题。只是将长链表分多组逆序,多了每组逆序后,向前向后链接的步骤。


class Solution {public:    ListNode *reverseKGroup(ListNode *head, int k) {        ListNode *p=head,*q=head;        ListNode *ghead,*gtail,*front=NULL,*back=NULL;                       while(p!=NULL){        int n=k-1;        while(n--){         if(p->next==NULL) return head;             p=p->next;        }//p指向长度为k的group的tail                        ghead=q;gtail=p;        back=p->next;              if(ghead==gtail)return head;        reverseList(ghead,gtail);        ghead=p;gtail=q;  //逆序后,收尾交换了        if(front==NULL){  //第一个分组         head=ghead;        }        else{        front->next=ghead;        }                front=gtail;        gtail->next=q=p=back;      }        return head;                      }private:     ListNode *reverseList(ListNode *head,ListNode *tail){          if(head==tail)return head;  //只有一个值                    tail=tail->next;          ListNode *p,*q,*temp;          p=head;q=head->next;          while(q!=tail){          temp=q;          q=q->next;          temp->next=p;          p=temp;          }          head->next=NULL;          head=p;          return head;             }};



0 0