首页 > 试题广场 >

转动链表

[编程题]转动链表
  • 热度指数:20266 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
将给定的链表向右转动k个位置,k是非负数。
例如:
给定1->2->3->4->5->null , k=2,
返回4->5->1->2->3->null。
示例1

输入

{1,2},1

输出

{2,1}

说明:本题目包含复杂数据结构ListNode,点此查看相关信息
我其实使用了一个取巧的方法,将链表所有元素都遍历一遍,然后使用列表的方法,最后一位删除一位元素然后初始再添加一位元素,直到计数达到k;操作完后,再构造一个链表就可以了
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Link:
    def __init__(self):
        self.head =  None
    def addlink(self,val):
        node1=ListNode(val)
        if self.head==None:
            self.head=node1
            return
        else:
            cur=self.head
            while(cur.next):
                cur=cur.next
            cur.next=node1
            return

#
#
# @param head ListNode类
# @param k int整型
# @return ListNode类
#
class Solution:
    def rotateRight(self, head, k):
        # write code here
        if head == None&nbs***bsp;k == 0:
            return head
        totallist=[]
        while(head):
            totallist.append(head.val)
            head=head.next
        while(k):
            totallist.insert(0,totallist.pop())
            k-=1
        l1=Link()
        for i in totallist:
            l1.addlink(i)
        return l1.head


发表于 2020-09-22 11:07:18 回复(1)

问题信息

难度:
1条回答 16359浏览

热门推荐

通过挑战的用户

查看代码