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个节点一组,反转,同时记录反转的数目num,到k之后重新计数,反转完毕之后,查看num数值,大于初始值,则将最后一组的链表再反转回来即可。代码如下:
public ListNode reverseKGroup(ListNode head, int k) { if(k < 2 || head == null){ return head; } int num = 1;//计数 ListNode pre = new ListNode(0);//定义头结点 pre.next = head; ListNode firstNode = pre;//保存头结点 ListNode next = null;//下一个节点 ListNode cur = head.next;//当前节点 ListNode curHead = head;//不随位置改变的头结点(如1,2,3),curHead =1;变为321后,curHead仍=1 while(cur != null){//当前节点不为null next = cur.next;//保存next节点 //交换节点 pre.next = cur; cur.next = head; curHead.next = next;//节点交换完成 //如果next==null,num+1与k比较后返回 if(next == null){ if(++num == k){ num = 1; } break; } //为下一循环准备 head = cur; cur = next; //如果已交换的节点==k,则pre等节点改变位置 if(++num == k){ num = 1; pre = curHead; curHead = cur; head = cur; cur = cur.next; } } //如果num>1表明最后不够k的节点也交换了,交换回来即可 if(num > 1){ curHead = head = pre.next; cur = head.next; while(cur != null){//与上述代码类似 next = cur.next; //交换数据 pre.next = cur; cur.next = head; curHead.next = next; //更新数据,准备下一循环 head = cur; cur = next; } } return firstNode.next; }
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if(k < 2 || head == null){ return head; } int num = k; ListNode p = head; //判断节点个数与k的大小 while(num > 1 && p != null){ p = p.next; num--; } if(p == null){//说明k比节点的个数大,直接返回 return head; } num = k;//再次赋初始值 p = head; ListNode q = null;//定义两个临时周转节点 ListNode r = null; while(num > 1){ q = p.next;//保存变量 r = q.next; //交换节点 q.next = head; p.next = r; //变量前进 head = q; num--; } p.next = reverseKGroup(p.next,k);//递归调用 return head; } }