存在一个按升序排列的链表,给你这个链表的头节点 head
,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表。
示例 1:
输入:head = [1,1,2] 输出:[1,2]
示例 2:
输入:head = [1,1,2,3,3] 输出:[1,2,3]
提示:
- 链表中节点数目在范围
[0, 300]
内 -100 <= Node.val <= 100
- 题目数据保证链表已经按升序排列
package Solution83;
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode header = new ListNode();
header.next = head;
ListNode cur = head;
while (cur != null && cur.next != null) {
if (cur.next.val == cur.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return header.next;
}
void printList(ListNode node) {
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
}
public static void main(String[] args) {
Solution sol = new Solution();
ListNode head = new ListNode(1);
head.next = new ListNode(1);
head.next.next = new ListNode(1);
head.next.next.next = new ListNode(1);
head.next.next.next.next = new ListNode(1);
// head.next.next.next.next.next = new ListNode(2);
sol.printList(sol.deleteDuplicates(head));
}
}