您的位置:首页 > Web前端 > Node.js

leetcode 25. Reverse Nodes in k-Group——很值得一看的链表题

2016-05-25 14:49 501 查看
//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 Solution {

static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}

public static void main(String[] args) {
ListNode p = new ListNode(1);
ListNode input = p;
for(int i = 0;i<6;i++){
ListNode a = new ListNode(i+2);
p.next = a;
p = p.next;
}
ListNode result = reverseKGroup(input,3);
while(result!=null){
System.out.println(result.val);
result = result.next;
}
}

public static ListNode reverseKGroup(ListNode head, int k) {
if(head == null || k == 1) return head;
ListNode dummy = new ListNode(0);												//在当前链表之前创建一个结点
dummy.next = head;
ListNode pre = dummy;															//是pre,dummy都为链表之前的这个结点
int i = 0;
while(head != null){
i++;
if(i % k ==0){																//为k的整数倍
pre = reverse(pre, head.next);
head = pre.next;														//head永远为pre之后的那个结点
}else {
head = head.next;														//找到要逆序排列链表的最后一个结点
}
}
return dummy.next;																//返回新建节点之后的链表
}

//将当前链表除首尾结点外的结点进行逆序连接,输出与尾结点相连的前一个节点
private static ListNode reverse(ListNode pre, ListNode next){						//画图才能理解
ListNode last = pre.next;
ListNode cur = last.next;
while(cur != next){
last.next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = last.next;
}
return last;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: