存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for singly-linked list.
* 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; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (null == head || null == head.next) {
return head;
}
// 这种删除节点的常用方式就是给一个哑节点
ListNode dummyNode = new ListNode(0, head);
ListNode cur = dummyNode;
while (null != cur.next && null != cur.next.next) {
if (cur.next.val == cur.next.next.val) {
while (null != cur.next && null != cur.next.next && cur.next.val == cur.next.next.val) {
cur.next = cur.next.next;
}
} else {
cur = cur.next;
}
}
return dummyNode.next;
}
}
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (null == head || null == head.next) {
return head;
}
// 不创建哑节点
ListNode cur = head;
while (null != cur.next) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (null == head || null == head.next) {
return head;
}
// 递归
if (head.val == head.next.val) {
ListNode node = head.next;
head.next = head.next.next;
node.next = null;
deleteDuplicates(head);
} else {
deleteDuplicates(head.next);
}
return head;
}
}