[LeetCode] 25. Reverse Nodes in k-Group

来源:互联网 发布:linux版本介绍 编辑:程序博客网 时间:2024/06/08 10:35

思路:
话说真是不擅于任何链表花式操作啊, 想了半天还是用了最传统的方法. 不停地找长度合法的区间, 如果找到区间, 就逆转那段链表, 找不到就可以直接返回了.

ListNode* reverseList(ListNode* start, ListNode* end) {    ListNode* pre = NULL, *cur = start, *nex = NULL;    while (true) {        nex = cur->next;        cur->next = pre;        if (cur == end) break;        pre = cur;        cur = nex;    }    // 别忘了逆转完的链表尾端要和后面的链表继续连接上    start->next = nex;    return cur;}ListNode* reverseKGroup(ListNode* head, int k) {    if (! head || ! head->next || k < 2) return head;    ListNode dummy(0);    dummy.next = head;    ListNode* pre = &dummy;    while (true) {        ListNode* tail = head;        int count = 0;        while (count < k - 1 && tail)             tail = tail->next, count++;        // 剩余的元素不够了, 就不逆转了, 直接返回        if (count <= k - 1 && ! tail) break;        pre->next = reverseList(head, tail);        pre = head;        head = head->next;    }    return dummy.next;}
0 0
原创粉丝点击