问题描述:

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

算法分析:这个k是可以超过链表长度的,所以要对k取模。

 

public ListNode rotateRight(ListNode head, int k) {
		int lenth = 0;//链表长度
		ListNode headd = head;
		while (headd != null) {
			lenth++;
			headd = headd.next;
		}
		if (head == null || head.next == null || k % lenth == 0) {
			return head;
		}

		ListNode headc = head;
		for (int i = 1; i < lenth - k % lenth; i++) {
			headc = headc.next;
		}
		ListNode newHead = headc.next;
		ListNode p = newHead;
		while (p.next != null) {
			p = p.next;
		}
		p.next = head;
		headc.next = null;

		return newHead;
	}

 

相关文章:

  • 2021-10-26
  • 2022-12-23
  • 2022-02-10
  • 2021-11-02
  • 2022-12-23
  • 2021-11-27
  • 2021-09-17
  • 2021-11-23
猜你喜欢
  • 2022-01-13
  • 2022-12-23
  • 2022-03-03
  • 2022-12-23
  • 2021-04-19
  • 2021-12-29
  • 2021-08-24
相关资源
相似解决方案