25. Reverse Nodes in k-Group

来源:互联网 发布:王欣认罪 知乎 编辑:程序博客网 时间:2024/06/05 12:49

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

k is a positive integer and is less than or equal to the length of the linked 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

思路:本题第一想法是用栈解决,这样思路很简单,但是细想以下会带来O(N)的构造过程,并用一个栈每次存储K个元素,会有额外的时间和空间复杂度,但还是先实现出来了,有总比没有强么,在链表内直接操作可能会麻烦一些,待会再说;

ListNode* reverseKGroup111(ListNode* head, int k) {    if (head == NULL || k <= 1)return head;    ListNode *newHead = new ListNode(-1);    ListNode *newHeadNode = newHead;    int len = 0;    ListNode *p = head;    //计算链表的长度,方便进行 len / k次循环    while (p){        p = p->next;        len++;    }    int cnt = len / k;    int count = 0;    stack<int> temp;    p = head;    if (cnt == 0) return head;    for (int i = 0; i < cnt; i++){        count = k;        while (count--){            temp.push(p->val);            p = p->next;        }        while (!temp.empty()){            ListNode *pp = new ListNode(temp.top());            temp.pop();            newHeadNode->next = pp;            newHeadNode = newHeadNode->next;        }    }    if (p)newHeadNode->next = p;    return newHead->next;}

思路2:在链表内进行操作,不需要额外的时间和空间复杂度,直接O(N);

ListNode *reverseNext(ListNode *head, int k){    if (head == NULL)return NULL;    ListNode *next = head;    for (int i = 0; i < k; i++){        if (next->next == NULL)return next;        next = next->next;    }    ListNode *n1 = head->next;    ListNode *prev = NULL;    ListNode *cur = n1;    for (int i = 0; i < k; i++){        ListNode *temp = cur->next;        cur->next = prev;        prev = cur;        cur = temp;    }    n1->next = cur;    head->next = prev;    return n1;}ListNode* reverseKGroup(ListNode* head, int k) {    if (head == NULL || k <= 1)return 0;    ListNode newHead(-1);    newHead.next = head;    head = &newHead;    while (head->next){        head = reverseNext(head, k);    }    return newHead.next;}
原创粉丝点击