博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] #25 Reverse Nodes in k-Group
阅读量:4705 次
发布时间:2019-06-10

本文共 1644 字,大约阅读时间需要 5 分钟。

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个长度的链表进行反转。时间:30ms

代码如下:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    bool isKLen(ListNode* head, int k){        if (k <= 0 || head == NULL)            return false;        ListNode *phead = head;        int count = k - 1;        while (phead->next != NULL&&count){            phead = phead->next;            count--;        }        if (count == 0)            return true;        else            return false;    }    ListNode* reverseKGroup(ListNode* head, int k) {        if (head == NULL || k <= 1)            return head;        ListNode *p, *q, *phead, *pnext = new ListNode(0);        pnext->next = p = head;        phead = pnext;        while (isKLen(p,k)){            int count = k-1;            ListNode *qt = pnext->next;            while (count--){                q = p->next;                p->next = q->next;                q->next = qt;                qt = q;            }            pnext->next = qt;            pnext = p;            p = p->next;        }        return phead->next;    }};

 

转载于:https://www.cnblogs.com/Scorpio989/p/4549794.html

你可能感兴趣的文章
图像形态学及更通用的形态学的原理及细节汇总
查看>>
linux开启coredump的3种方法
查看>>
数据驱动之 python + requests + Excel
查看>>
小鸡啄米问题求解
查看>>
Castle.net
查看>>
HDU1532 网络流最大流【EK算法】(模板题)
查看>>
POJ 2594 Treasure Exploration (Floyd+最小路径覆盖)
查看>>
数字图像处理 博客目录索引
查看>>
nodejs+redis使用
查看>>
prime算法的使用
查看>>
Jedis - hello world
查看>>
Ehcache(2.9.x) - API Developer Guide, Cache Eviction Algorithms
查看>>
把最近这些安全的问题整理一下
查看>>
【转】如何避免OOM总结
查看>>
java 类与对象
查看>>
git push 每次都要输入用户名密码
查看>>
远程桌面无法复制粘贴
查看>>
对错排认识。
查看>>
js高级程序设计——数据属性和访问器属性
查看>>
C# App.config 自定义 配置节
查看>>