题目要求:
分析:
我是因为看到这道题目可以用递归,才来做的,结果,第一反应永远是直接暴力的方法……
直接上代码吧
具体代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode cur = head;
while(cur != null && cur.next != null) {
if(cur.val == cur.next.val)
cur.next = cur.next.next;
else
cur = cur.next;
}
return head;
}
}
我硬是想不出来用递归怎么做,不知道从哪里入手,等会儿去看看别人怎么做。
我!真的!!震惊了!!!这个是那篇递归科普文的原作者写的:
具体代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;
head.next = deleteDuplicates(head);
if(head.val == head.next.val)
head = head.next;
return head;
}
}