【原创】leetCodeOj ---Remove Duplicates from Sorted List II 解题报告
明日深圳行,心情紧张,写博文压压惊 囧
-------------------------------------
原题地址:
https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
题目内容:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
方法:
递归做非常直观。
判断当前节点的值是否等于下一个节点的值,若不等,直接递归调用下一个节点;
若相等,则找到下一个不和当前节点相等的节点,并将其更新为当前节点,同时递归调用该节点。
全部代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null) return null; if (head.next == null) return head; if (head.next.val == head.val) { while (head.next != null && head.next.val == head.val) { head = head.next; } head = deleteDuplicates(head.next); } else { head.next = deleteDuplicates(head.next); } return head; } }
posted on 2014-11-23 21:07 shadowmydx'sLab 阅读(103) 评论(0) 编辑 收藏 举报