[LeetCode] 83. Remove Duplicates from Sorted List 移除有序链表中的重复项
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
移除有序链表中的重复项,返回新链表。定义1个指针指向链表的第一个元素,然后第一个元素和第二个元素比较,如果重复,则删掉第二个元素,如果不重复,指针指向第二个元素。
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null ) return head; ListNode c = head; while (c.next != null ) { if (c.val == c.next.val) { c.next = c.next.next; } else { c = c.next; } } return head; } } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class Solution( object ): def deleteDuplicates( self , head): """ :type head: ListNode :rtype: ListNode """ cur = head while cur: runner = cur. next while runner and runner.val = = cur.val: runner = runner. next cur. next = runner cur = runner return head def deleteDuplicates2( self , head): """ :type head: ListNode :rtype: ListNode """ if not head: return head if head. next : if head.val = = head. next .val: head = self .deleteDuplicates(head. next ) else : head. next = self .deleteDuplicates(head. next ) return head |
Python: wo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution( object ): def deleteDuplicates( self , head): """ :type head: ListNode :rtype: ListNode """ if not head: return None dummy = ListNode( 0 ) dummy. next = head while head and head. next : if head.val = = head. next .val: head. next = head. next . next else : head = head. next return dummy. next |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Solution { public : ListNode *deleteDuplicates(ListNode *head) { if (!head || !head->next) return head; ListNode *start = head; while (start && start->next) { if (start->val == start->next->val) { ListNode *tmp = start->next; start->next = start->next->next; delete tmp; } else start = start->next; } return head; } }; |
类似题目:
[LeetCode] 82. Remove Duplicates from Sorted List II 移除有序链表中的重复项 II
[LeetCode] 19. Remove Nth Node From End of List 移除链表倒数第N个节点
[LeetCode] 203. Remove Linked List Elements 移除链表元素
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步