5

#yyds干货盘点# leetcode算法题: K 个一组翻转链表

 2 years ago
source link: https://blog.51cto.com/u_13321676/5372357
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# leetcode算法题: K 个一组翻转链表

原创

灰太狼_cxh 2022-06-10 09:52:30 博主文章分类:leetcode ©著作权

文章标签 链表 代码实现 i++ 文章分类 Java 编程语言 阅读数165

给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。

k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

输入:head = [1,2,3,4,5], k = 2

输出:[2,1,4,3,5]

输入:head = [1,2,3,4,5], k = 3

输出:[3,2,1,4,5]

代码实现:

class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || head.next == null) return head;

ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode cur = head;
int count = 0;
while(cur != null)
{
cur = cur.next;
count++;
}
int timesToFlip = count / k;
cur= head;
ListNode before = dummyHead;
ListNode after = null;
for(int i = 0; i < timesToFlip; i++)
{
int numNodes = k;
ListNode temp = null, pre = null;

//Reverse partial Linked-list
while(numNodes != 0)
{
numNodes--;

temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
after = cur;
}
before.next = pre;
while(pre.next != null)
pre = pre.next;
pre.next = after;
before = pre;
cur = before.next;
}

return dummyHead.next;
}
}
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK