本文共 1342 字,大约阅读时间需要 4 分钟。
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
public class Test_78 { public static ListNode reverseKGroup(ListNode head, int k) { ListNode tmp = head; for (int i = 0; i < k; i++) { if (null == tmp) { return head; } else { tmp = tmp.next; } }//将链表根据基数k分隔,tmp指向下一k个节点的第一个 ListNode tmp_2 = head; for (int i = 0; i < k - 1; i++)//获得基数k中的最后一个节点 tmp_2 = tmp_2.next; tmp_2.next = head;//收尾相连 ListNode tmp_3=null; int count =k-2; while(count >0) //实现前k个节点的 { count--; tmp_3 = head.next; head.next = head.next.next; tmp_3.next = tmp_2.next; tmp_2.next=tmp_3; } head.next = reverseKGroup(tmp, k); head = tmp_2; return head; } public static void main(String[] arqs) { ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); head = reverseKGroup(head, 3); while(null != head){ System.out.println(head.val); head = head.next; } }}
转载地址:http://qpuni.baihongyu.com/