本文主要是介绍leetcode解题方案--025--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.
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
分析
这道题用的是链表局部反转加递归
如果要反转一个链表,应该是这样的
//header 是要反转的链表头 num是翻转的结点数,循环次数+1,翻转节点若为5,则只需4条线变化方向ListNode p = header;ListNode q,r;q = p.next;n = num;//链表的反转while (--n>0) {r = q.next;q.next = p;p=q;q=r;}return p;
public static ListNode reverseKGroup(ListNode header, int num) {if (num==1) {return header;}ListNode end = header;int n = num;//到达第n个节点while (--n>0) {if (end == null||end.next == null) {return header;} else {end = end.next;}}end = end.next;ListNode p = header;ListNode q,r;q = p.next;n = num;//链表的反转while (--n>0) {r = q.next;q.next = p;p=q;q=r;}header.next = reverseKGroup(end, num);print(p);return p;}
虽然不是最优的,但也算是全过了,还是挺开心的
这篇关于leetcode解题方案--025--Reverse Nodes in k-Group的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!