Leetcode #25 Reverse Nodes in k-Group

来源:互联网 发布:matlab数据转换 编辑:程序博客网 时间:2024/04/29 12:38

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


Difficulty: Hard


Use two pointer change the "next pointer"" from back to beginning in each group.

(Use three pointers seems to be a better method)


/** * 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) {        int len = 1;        if(head==NULL)            return NULL;        ListNode* current = head;        while(current->next != NULL){            current = current->next;            len++;        }        if(len<k||k==1)            return head;        current = head;        ListNode* last_end = new ListNode(0);        last_end->next = head;        ListNode* current_next = NULL;        ListNode* current_end = NULL;        ListNode* next_start = NULL;                ListNode* start = last_end;                for(int i = 0; i<len/k;i++){            current = last_end->next;            current_next = current->next;            for(int j = k-2;j>=0;j--){                ListNode* temp = current;                ListNode* tempNext = current_next;                for(int k = 0;k<j;k++){                    temp = temp->next;                    tempNext = tempNext -> next;                }                if(j == k-2){                    current_end = tempNext;                    next_start = tempNext->next;                }                tempNext->next = temp;            }            last_end->next = current_end;            current->next = next_start;            last_end = current;        }                return start->next;    }};



0 0
原创粉丝点击