25. Reverse Nodes in k-Group

来源:互联网 发布:python 私有成员获取值 编辑:程序博客网 时间:2024/05/18 00:52

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

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseKGroup(ListNode* head, int k) {        if(!head)            return NULL;        int len = 0;        ListNode *cur = head;        while(cur)        {            ++len;            cur = cur->next;        }        //if the length of the list is smaller than k,return          if(len<k)            return head;        ListNode *dummy = new ListNode(INT_MAX);        dummy->next = head;        ListNode *prev = dummy;        cur = head;        ListNode *next = cur->next;        //save value of k in a tmp variable        int kOrigin = k;        //revers the k list nodes        while(cur && k>0)        {            cur->next = prev;            prev = cur;            cur = next;            if(next)                next = next->next;            --k;        }        //set the pointers        dummy->next = prev;        head->next = NULL;        //recurse        if(cur)            head->next = reverseKGroup(cur,kOrigin);                    return dummy->next;                    }};



跟Swap Nodes in Pairs思路类似,也要用递归,只不过把swap换成了reverse;

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseKGroup(ListNode* head, int k) {        if(!head || !head->next || k<=1)            return head;                ListNode *p = head;        //计算链表的长度        int len = 0;        while(p)        {            len++;            p = p->next;        }                //如果k>len,直接返回输入链表        if(k > len)            return head;        p = NULL;        ListNode *q = head;        int kTmp = k;        //将长度为k的链表reverse        while(q && kTmp>0)        {            ListNode *tmp = q->next;            q->next = p;            p = q;            q = tmp;            kTmp--;        }                //如果剩余链表的长度>k,则继续reverse        if(len-k >= k)            head->next = reverseKGroup(q,k);        //否则,将后续链表直接接上        else            head->next = q;                        return p;            }};


0 0
原创粉丝点击