题目:给定一个链表,删除链表里的重复元素(相同的元素只能在链表里出现一次)
难度:Easy
思路:对于链表操作的题目一般需要判头判空判尾,然后就是根据需要定义几个指针,对于此题只需要定义两个指针curr,next(一个指向当前元素,另一个根据是否和curr指针指向的值是重复元素来进行一定)
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode curr = head;
ListNode next = curr.next;
while(next != null){
while(next != null && curr.val == next.val){
next = next.next;
}
if(next == null){
curr.next = null;
}else if(curr.val != next.val){
curr.next = next;
curr = next;
next = next.next;
}
}
return head;
}
}
- 来自Discuss里的解题方法(利用递归来做)
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)return head;
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}
LeetCode上大部分的链表操作算法题都能用递归实现