链表——循环右移链表的后K个结点

题目:输入k和链表的头结点,循环右移链表的后K个结点。


For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.


思路:

1.首先要找链表的倒数第K个结点;

2.因循环右移的K个结点仍是按原来顺序排列,可考虑用一个先进先出的容器即队列后K个结点

存储,依次连接在链表首处;

3.但此解法空间复杂度为O(k);

4.将链表首尾相接成环,然后在第K个结点前的结点处断开即可;


因leetcode上测试用例中的k有大于length of list 的情况,故要先遍历一遍然后使k=k%(length of list),

时间复杂度仍为O(n).


代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if(head==null||head.next==null)
            return head;                 
        
        //测试用例中有n大于length of list的情况;
        ListNode temp=head;
        int count =1;
        while(temp.next!=null)
            {
            temp=temp.next;
            count++;
        }
            n=n%count;
        
        if(0 == n)
            return head;  
                
        ListNode first=head;
        ListNode second=head;
        
        //先找到倒数第n个结点;
        int num=1;  
        while(num<n&&second!=null)
            {
            second=second.next;
            num++;//while循环中一定要注意别少了对变量的修改,避免进入死循环;
        }
       
        //firstpre记录倒数第n个结点的上一个结点;
        ListNode firstpre=first;
        while(second.next!=null)
            {
            firstpre=first;
            first=first.next;
            second=second.next;
        }  
        second.next=head;
        head=first;
        firstpre.next=null;
        
        return head;               
    }
}


 


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值