删除链表的节点

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

 1 class Solution:
 2     def deleteDuplication(self, pHead):
 3         if pHead == None or pHead.next == None:
 4             return pHead
 5         n = pHead.next
 6         if pHead.val == n.val:
 7             while n and pHead.val == n.val:
 8                 n = n.next
 9             return self.deleteDuplication(n)
10         else:
11             pHead.next = self.deleteDuplication(pHead.next)
12             return pHead
13         # write code here

 

leetcode上的Java版本,此题对比原题有改动:

 1 class Solution {
 2     public ListNode deleteNode(ListNode head, int val) {
 3         if (head == null) {
 4             return null;
 5         }
 6         ListNode dHead = new ListNode(-1);
 7         dHead.next = head;
 8         ListNode temp = dHead;
 9         while (temp.next != null) {
10             int cur = temp.next.val;
11             if (cur == val) {
12                 temp.next = temp.next.next;
13                 return dHead.next;
14             }
15             temp = temp.next;
16         }
17         return null;
18     }
19 }

 

posted on 2019-06-13 15:33  Sempron2800+  阅读(118)  评论(0编辑  收藏  举报