LeetCode algorithm exercise (rotating linked list)

本文内容:
1、题目
2、我的正确解答

1、题目

Given a linked list, rotate the linked list k positions to the right, where k is a non-negative number.

示例:

给定 1->2->3->4->5->NULL 且 k = 2,

返回 4->5->1->2->3->NULL.

2、我的正确解答

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null)
            return head;
        //计算链表长度
        int len = 1;
        ListNode $temp1 = head;
        while($temp1.next!=null){
            $temp1 = $temp1.next;
            len++;
        }
        k = k % len;
        if(k==0)
            return head;
        //找到旋转的起点    
        int count = 1;
        ListNode $temp2 = head;
        while(count != (len-k)){
            $temp2 = $temp2.next;
            count++;
        }
        //保存新的头结点
        ListNode $temp3 = $temp2.next;
        //尾节点指向空
        $temp2.next = null;
        //将原来的尾节点指向原来的头结点
        $temp1.next = head;
        //返回现在的头结点
        return $temp3;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325407494&siteId=291194637