/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode DeleteDuplicates(ListNode head) { //if (head == null || head.next == null) //{ // return head; //} //head.next = DeleteDuplicates(head.next); //if (head.val == head.next.val) //{ // return head.next; //} //else //{ // return head; //} if (head != null) { var cur = head; var next = head.next; while (next != null) { if (cur.val == next.val) { cur.next = next.next;//对原链表的修改 } else { cur = next;//移动指针 } next = next.next;//移动指针 } } return head; } }
https://leetcode.com/problems/remove-duplicates-from-sorted-list/#/description
补充一个python的实现:
1 class Solution: 2 def deleteDuplicates(self, head: ListNode) -> ListNode: 3 if head == None: 4 return None 5 cur = head 6 nextnode = head.next 7 while nextnode != None: 8 if cur.val == nextnode.val: 9 cur.next = nextnode.next 10 else: 11 cur = nextnode 12 nextnode = nextnode.next 13 return head
python另一种写法:
1 class Solution: 2 def deleteDuplicates(self, head: ListNode) -> ListNode: 3 if head == None: 4 return None 5 temp = ListNode(-1) 6 temp.next = head 7 nextnode = head.next 8 while head != None and nextnode != None: 9 if head.val != nextnode.val: 10 head.next = nextnode 11 head = head.next 12 else: 13 nextnode = nextnode.next 14 head.next = None 15 return temp.next