码迷,mamicode.com
首页 > 编程语言 > 详细

Java [leetcode 25]Reverse Nodes in k-Group

时间:2015-05-15 21:20:39      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

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个数字为一段的方法递归判断。如果该段长度不够k,那么直接返回该段的值。否则将该段k个数字从第一个数字开始两个两个反转。

代码如下:

public ListNode reverseKGroup(ListNode head, int k) {
		if (head == null)
			return null;
		ListNode tmp = head;
		for (int i = 1; i < k; i++) {
			tmp = tmp.next;
			if (tmp == null)
				return head;
		}
		ListNode nextRoundHead = tmp.next;
		ListNode firstNode = head;
		ListNode secondNode = head.next;
		ListNode thirdNode;
		for (int i = 1; i < k; i++) {
			thirdNode = secondNode.next;
			secondNode.next = firstNode;
			firstNode = secondNode;
			secondNode = thirdNode;
		}
		head.next = reverseKGroup(nextRoundHead, k);
		return tmp;
	}

 

Java [leetcode 25]Reverse Nodes in k-Group

标签:

原文地址:http://www.cnblogs.com/zihaowang/p/4506748.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!