您当前的位置: 首页 >  链表
  • 0浏览

    0关注

    674博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

旋转链表

沙漠一只雕得儿得儿 发布时间:2016-11-16 15:43:30 ,浏览量:0

package 链表下;

/**
 * 旋转链表
 * 
 * @author buder_cp
 *
 */
public class rotateList {
	/**
	 * 获取链表长度
	 * 
	 * @param head
	 * @return
	 */
	public static int lengthOfList(ListNode head) {
		ListNode p = head;
		int n = 0;
		while (p != null) {
			p = p.next;
			n++;
		}
		return n;
	}

	public static ListNode rotateRight(ListNode head, int k) {
		ListNode pre = head;
		int n = lengthOfList(head);
		for (int i = 1; i < n - k; i++) {
			pre = pre.next; // pre是前半部分的尾节点
		}
		ListNode newHead = pre.next;
		ListNode last = newHead; // newHead是断开的新的头结点
		while (last.next != null) {
			last = last.next;
		}
		pre.next = null; // 开始改变指针,pre是新的尾部节点,指向null
		last.next = head; // last是断开的尾部节点,并与前半部分链接起来
		return newHead;
	}

	public static void main(String[] args) {
		int[] array = { 1, 2, 3, 4, 5, 6, 7, 8 };
		ListNode head = ListNode.arrayToList(array);
		head = rotateRight(head, 2);
		ListNode.printList(head);
	}
}
关注
打赏
1657159701
查看更多评论
立即登录/注册

微信扫码登录

0.0367s