首页 > 代码库 > LeetCode——Reverse Nodes in k-Group

LeetCode——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


原题链接:https://oj.leetcode.com/problems/reverse-nodes-in-k-group/

题目:给定一个链表,一次反转链表的k个值,并返回逆转后的结果链表。如果节点的数量不是k的倍数,那么保留原来的样子。

思路:如果将链表转成数组来做的话,就更加方便了。但是这里还是用链表来逆转,其实思路是一样的,遇到k个长度就将这k个节点逆转就可以了。

	public ListNode reverseKGroup(ListNode head, int k) {
		if (head == null || k <= 1)
			return head;
		ListNode dummy = new ListNode(-1);
		dummy.next = head;
		int count = 0;
		ListNode pre = dummy,current = head;
		while (current != null) {
			count++;
			ListNode post = current.next;
			if(count == k){
				pre = reverse(pre,post);
				count = 0;
			}
			current = post;
		}
		return dummy.next;
	}
	
	ListNode reverse(ListNode pre,ListNode post){
		ListNode dummy = pre.next;
		ListNode current = dummy.next;
		while(current != post){
			ListNode next = current.next;
			current.next = pre.next;
			pre.next = current;
			current = next;
		}
		dummy.next = post;
		return dummy;
	}
	// Definition for singly-linked list.
	public class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
			next = null;
		}
	}


LeetCode——Reverse Nodes in k-Group