Rotate List

来源:互联网 发布:中国税务网络大学手机 编辑:程序博客网 时间:2024/05/24 06:53

问题描述

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.

思考:用两个指针A,B,A先走k步,然后A、B同时

想法

  • 1、A先走k步,然后A、B同时,直到A到表尾
  • 2、head指向B的next;
  • 3、将A的next指向表头,B的next置为null;

代码

public class Solution {    public ListNode rotateRight(ListNode head, int k) {        ListNode first = head;        ListNode second = head;        if(head == null || head.next == null)            return head;        int sum = 0;        while(k > 0){            first = first.next;            sum++;            k--;            if(first == null){                first = head;                k = k % sum;            }        }        while(first.next != null){            first = first.next;            second = second.next;            if(second == null)                second = head;        }        first.next = head;        head = second.next;        second.next = null;        return head;    }}
0 0
原创粉丝点击