Remove-Duplicates-From-Sorted-List.——python

“””
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3.
“”“

class Solution(object):
    def deleteDuplicates(self,head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        list = ListNode(None)
        list.next = head
        p = list

        while p and p.next:
            if p.val == p.next.val:
                p.next = p.next.next
            else:
                p = p.next
        return list.next

实现链表总体需要两步:定义链表和对链表进行操作

1.定义链表:

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

2.对链表进行操作 添加新的node,反向排序链表,打印链表

class ListNode_handle:
    def __init__(self):
        self.cur_node = None

    def add(self,data):
        node = ListNode()
        node.val = data
        node.next = self.cur_node
        self.cur_node = node
        return node
    def print_ListNode(self,node):
        while node:
            print('\nnode:',node,'value:',node.val,'next:',node.next)
            node = node.next
    def __reversed__(self,nodelist):
        list = []
        while nodelist:
            list.append(nodelist.val)
            nodelist = nodelist.next
        result = ListNode()
        result_handle = ListNode_handle()
        for i in list:
            result = result_handle.add(i)
        return  result
发布了84 篇原创文章 · 获赞 30 · 访问量 7万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览