链表的操作

链表的建立:

首先建立节点:

class ListNode():
    def __init__(self,value):
        self.val=value
        self.next=None

建立链表:

def createList(num):
    if num<=0:
        return None
    head=None
    val=0
    node=None
    while num>0:
        if head is None:
            head=ListNode(val)   #为了保存head头节点的位置不变化
            node=head
        else:
            node.next=ListNode(val)
            node=node.next
        val+=1
        num-=1
    return head

head=createList(5)
while head is not None:
    print("{0}->".format(head.val),end=' ')
    head=head.next

 

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

输入: 1->2->3->4->5->NULL, k = 2

输出: 4->5->1->2->3->NULL

解释: 向右旋转 1 步: 5->1->2->3->4->NULL

         向右旋转 2 步: 4->5->1->2->3->NULL

 

思路:第一步建立节点。 第二步建立链表。  第三步,建立旋转函数。

旋转函数的思路为:将一个链表首尾相连。然后判断需要挪动的位置。把头指针放到挪动后的位置。这个时候需要注意的是,此时的链表仍然是首尾相连的。应该从头节点指针位置的地方断开。

 

class ListNode():
    def __init__(self,value):
        self.val=value
        self.next=None

#可以考虑先把链表变成一个环形
def xuanzhuan(head,K):
    p=head
    count=1
    while p.next !=None:
        p=p.next
        count+=1
    p.next=head
    K%=count #移动的位数
    for i in range(count-K-1):
        head=head.next
    #断开
    p=head
    head=head.next
    p.next=None
    return head

def createList(num):
    if num<=0:
        return None
    head=None
    # val=0
    val=1
    node=None
    while num>0:
        if head is None:
            head=ListNode(val)   #为了保存head头节点的位置不变化
            node=head
        else:
            node.next=ListNode(val)
            node=node.next
        val+=1
        num-=1
    return head

head=createList(5)
p=head
while p is not None:
    print("{0}->".format(p.val),end=' ')
    p=p.next
print()

head=xuanzhuan(head,2)
while head is not None:
    print("{0}->".format(head.val),end=' ')
    head=head.next

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值