[leetcode] 25. Reverse Nodes in k-Group 解题报告

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq508618087/article/details/50481199

题目链接:https://leetcode.com/problems/reverse-nodes-in-k-group/

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


思路:上了一天课,晚上又连续做了几个小时题,感觉已经意识模糊了,题意看了好久没看懂。

这题是说给一个链表和k,每k个结点作为一段翻转一下。可以先计算出链表的长度,然后可以知道有几个需要翻转的区域,然后循环就地逆置那个区域的链表。如果最后一段剩余的长度小于k了,那就扔那不管了.

代码如下:

/**
 * 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 || k<=1) return head;
        ListNode *pHead=new ListNode(0), *p=pHead, *q=head, *tem;
        pHead->next = head;
        int len = 0;
        while(p->next) p = p->next, len++;
        p = pHead;
        while(len>=k)
        {
            int step = 1;
            q = p->next;
            while(step++ < k)
            {
                tem = q->next;
                q->next = tem->next;
                tem->next = p->next;
                p->next = tem;
            }
            p = q, len -= k;
        }
        head = pHead->next;
        delete pHead;
        return head;
    }
};


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页