当前位置: 移动技术网 > IT编程>开发语言>C/C++ > 【LeetCode OJ 061】Rotate List

【LeetCode OJ 061】Rotate List

2018年03月29日  | 移动技术网IT编程  | 我要评论

列布妮斯卡雅,买家信用,新东方考研网络课程

题目:Given a list, rotate the list to the right bykplaces, wherekis non-negative.

For example:
Given1->2->3->4->5->NULLandk=2,
return4->5->1->2->3->NULL.

解题思路:题意为给定一个链表,要求按照给定的位置进行反转。示例代码如下:

public class Solution
{
	  public ListNode rotateRight(ListNode head, int k) 
	  {
		if (head == null)
			return null;
		ListNode p = head;
		ListNode q = head;
		int num = 1;//统计链表元素个数
		while (p.next != null)
		{
			num++;
			p = p.next;//p指向尾节点
		}
		int n = 1;
		if (k >= num)
			k = k % num;//处理循环反转的情况
		while (n < num - k)
		{
			n++;
			q = q.next;
		}
		ListNode h = null;
		if (q.next != null)
		{
			//将q后面的节点作为新的头结点
			h = q.next;
			q.next = null;
			p.next = head;
		} 
		else
		{
			h = head;
		}
		return h;

	  }
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网