zoukankan      html  css  js  c++  java
  • 83.Remove Duplicates from Sorted List

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def deleteDuplicates(self, head: ListNode) -> ListNode:
            ans = []
            res = ListNode(0)
            res_s = res
            if not head:
                return None
            while head:
                if head.val not in ans:
                    ans.append(head.val)
                head = head.next
            for i in range(len(ans)):
                tmp = ListNode(ans[i])
                res.next = tmp
                res = res.next
            return res_s.next

    Java 版:

      • 遍历一遍链表,将不相等的加入到结果链表中,如果相等就跳过。

    class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head == null) return null;
            ListNode res = head, tmp = head;
            head = head.next;
            while(head != null){
                if(head.val != tmp.val){ //不相等时,加入结果集中
                    tmp.next = head;
                    tmp = tmp.next;
                }
                head = head.next;
            }
            tmp.next = null; //后续节点置 null
            return res;
        }
    }
  • 相关阅读:
    wxpython快速入门
    python核心编程 第四章 和第五章
    python核心编程 第三章
    python核心编程 第二章 快速入门
    Nginx 使用札记
    PHP 函数总结
    node.js安装部署
    linux
    在Linux上安装Git
    php超级全局变量
  • 原文地址:https://www.cnblogs.com/luo-c/p/12857235.html
Copyright © 2011-2022 走看看