迭代法:
/**
* 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) return head;
ListNode p = head.next;
ListNode pre = head;
int lastVal = head.val;
while(p!=null)
{
if(p.val==lastVal)
{
pre.next = p.next;
p.next = null;
p = pre.next;
}
else
{
lastVal = p.val;
p = p.next;
pre = pre.next;
}
}
return head;
}
}
官方题解:
public ListNode deleteDuplicates(ListNode head) {
ListNode current = head;
while (current != null && current.next != null) {
if (current.next.val == current.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
java中无需对结点进行free()操作?