【LeetCode】C# 61、Rotate List

来源:互联网 发布:开淘宝店需要电脑吗 编辑:程序博客网 时间:2024/05/19 06:51

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.

给定链表和value k,在链表第k位翻转。

思路:设定三个链表指针,fast指向末端,slow指向断点,dummy作为链表头,后通过

fast.next=dummy.next;dummy.next=slow.next;slow.next=null;

完成翻转。

/** * Definition for singly-linked list. * public class ListNode { *     public int val; *     public ListNode next; *     public ListNode(int x) { val = x; } * } */public class Solution {    public ListNode RotateRight(ListNode head, int k) {        if (head==null||head.next==null) return head;        ListNode dummy=new ListNode(0);        dummy.next=head;        ListNode fast=dummy,slow=dummy;        int i;        for (i=0;fast.next!=null;i++)//Get the total length             fast=fast.next;        for (int j=i-k%i;j>0;j--) //Get the i-n%i th node            slow=slow.next;        fast.next=dummy.next; //Do the rotation        dummy.next=slow.next;        slow.next=null;        return dummy.next;    }}
原创粉丝点击