Reverse Nodes in k-Group

来源:互联网 发布:网络投标书 编辑:程序博客网 时间:2024/06/15 20:09

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

思路:每组的reverse都一样,可以递归解决。

在每一组reverse时候:例如X->1->2->3, k=2

X是人为设置的一个头节点(每一组逆序都是如此),然后tail=1,cur=2,next=3;

1. 2->next=1(cur->[X->next])

2. X->next=2 (X->next=cur)

3. 2=3(cur=next)此时的cur为下一组的起始点。

4. tail->next=下一组的头

int list_length(ListNode *head){    int i = 0;    while (head)    {        i++;        head = head->next;    }    return i;}ListNode *reverse_list(ListNode *head){    if (head == NULL || head->next == NULL)        return head;    ListNode *pre = NULL, *cur = head, *next;    while (cur != NULL)    {        next = cur->next;        cur->next = pre;        pre = cur;        cur = next;    }    return pre;}ListNode *reverseKGroup(ListNode *head, int k){    if (list_length(head) < k || k < 2)        return head;    ListNode *newhead = head, *tail = head, *next_ghead;    for (int i = 0; i < k - 1; ++i)    {        tail = tail->next;    }    next_ghead = tail->next;    tail->next = NULL;    tail = reverse_list(newhead);    newhead->next = reverseKGroup(next_ghead, k);    return tail;}


0 0
原创粉丝点击