标签:des style blog http io color sp for on
明日珠海行,心情紧张,写博文压压惊 囧
-------------------------------------
原题地址:
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; } }
【原创】leetCodeOj ---Remove Duplicates from Sorted List II 解题报告
标签:des style blog http io color sp for on
原文地址:http://www.cnblogs.com/shadowmydx/p/4117447.html