-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSolution0083.java
More file actions
53 lines (47 loc) · 1.47 KB
/
Copy pathSolution0083.java
File metadata and controls
53 lines (47 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// 83. 删除排序链表中的重复元素
/**
* 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; }
* }
*/
/*
1、创建哨兵节点标记链表头部,用于删除节点后返回链表
2、使用前后两个指针pre、head来标记节点位置,通过判断head不为空来循环遍历,从而保证能获取前后两个节点的值来判断
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode root = new ListNode(-101, head);
ListNode pre = root;
while (head != null) {
if (head.val == pre.val) {
pre.next = head.next;
} else {
pre = head;
}
head = head.next;
}
return root.next;
}
}
/*
1、head为链表头部不变,用于删除节点后返回链表
2、使用一个指针cur标记节点,通过判断cur和cur.next不为空来循环遍历,从而保证能获取前后两个节点的值来判断
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode cur = head;
while (cur != null && cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}