File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ # No.83 删除排序链表中的重复元素
2+
3+ 难度: ` easy `
4+
5+ 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
6+
7+ ## 示例
8+
9+ 示例 1:
10+
11+ ```
12+ 输入: 1->1->2
13+ 输出: 1->2
14+ ```
15+ 示例 2:
16+ ```
17+ 输入: 1->1->2->3->3
18+ 输出: 1->2->3
19+ ```
20+
21+ ## 解题思路
22+
23+ 使用双指针,判断前后值是否相等。如果相等,则rear指针向后移动,如果不想等,则prev指针和rear指针同时向后移动。
24+
25+ 代码如下:
26+
27+ ``` javascript
28+ /**
29+ * Definition for singly-linked list.
30+ * function ListNode(val) {
31+ * this.val = val;
32+ * this.next = null;
33+ * }
34+ */
35+ /**
36+ * @param {ListNode} head
37+ * @return {ListNode}
38+ */
39+ var deleteDuplicates = function (head ) {
40+ if (! head)
41+ return head;
42+ let prev = head;
43+
44+ let rear = prev .next ;
45+
46+ while (rear) {
47+ if (prev .val == rear .val ) {
48+ prev .next = rear .next ;
49+ rear = rear .next ;
50+ } else {
51+ rear = rear .next ;
52+ prev = prev .next ;
53+ }
54+ }
55+ return head;
56+ };
57+ ```
You can’t perform that action at this time.
0 commit comments