python 实现单链表

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

class Solution:
    def CreateList(self, nums):
        head = tail = ListNode(-1)      # 在链表中,有首节点、头节点的区别。头节点是指向链表的第一个元素,首节点是指向链表头节点的前一个元素,一般表示链表的开始。
        for i in range(len(nums)):
            newNode = ListNode(nums[i])
            tail.next = newNode
            tail = newNode
        return head.next

    def DeleteNode(self, head, num):        # 删除值为 num 的链表节点
        if head.val == num:
            return head.next        # 如果要删除的是头节点,直接返回head.next
        pre, cur = head, head.next      # 删除节点操作需要有指向当前节点的指针和指向当前节点前一个元素的指针。
        while cur:
            if cur.val == num:      # 当前节点就是要找到的节点
                pre.next = cur.next
                cur.next = None
                break
            else:       # 如果不是,就一直遍历下去,直到链表遍历结束
                pre, cur = cur, cur.next
        return head

    def InsertNode(self, head, index, value):      # 在指定位置插入节点,若大于链表长度,则返回-1,位置索引从 1 开始
        # 要注意头、尾节点的插入方式与中间节点的不同
        newNode = ListNode(value)
        cnt = 2     # 从第二个节点开始,因为首节点已经先做过判断
        if index == 1:
            newNode.next = head
            head = newNode      # 统一返回 head 指针
        pre, cur = head, head.next
        while cur:
            if cnt == index:
                newNode.next = cur
                pre.next = newNode
                break
            else:
                cnt += 1
                pre, cur = cur, cur.next
        if cnt <= index:        # 如果大于链表中节点数目,则直接加到链表尾部
            pre.next = newNode
        return head

    def PrintList(self, head):      # 打印链表
        while head:
            print(head.val, end=' ')
            head = head.next

if __name__ == '__main__':
    nums = [2, 7, 1, 4, 5]
    a = Solution()
    head = a.CreateList(nums)
    # head = a.InsertNode(head, 6, 3)
    # head = a.DeleteNode(head, 2)
    a.PrintList(head)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值