存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。返回同样按升序排列的结果链表。
难度:简单。
思路:由于链表已经排好序了,所以我们只需要进行相邻元素两两比较即可,比较简单。本题属于链表类型的题目。
使用单指针或者递归可解,下面介绍两种解法!
/**
* 83. 删除排序链表中的重复元素
* 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
* https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
*/
public class LeetCode83{
/**
* 指针
*
* @param head
* @return
*/
public ListNode deleteDuplicates( ListNode head ){
ListNode curr = head;
while( curr != null && curr.next != null ){
if( curr.next.val == curr.val ){
curr.next = curr.next.next;
}
else{
curr = curr.next;
}
}
return head;
}
/**
* 递归
*
* @param head
* @return
*/
public ListNode deleteDuplicates1( ListNode head ){
if( head == null || head.next == null ){
return head;
}
head.next = deleteDuplicates( head.next );
return head.val == head.next.val ? head.next : head;
}
public class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode( int val ){ this.val = val; }
ListNode( int val, ListNode next ){
this.val = val;
this.next = next;
}
}
}
如有需要交流,或者文章有误,请直接留言。另外希望点赞、收藏、关注,我将不间断更新各种Java学习博客!