File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ *
3+ * Given a sorted linked list, delete all duplicates such that each element appear only once.
4+ *
5+ * For example,
6+ * Given 1->1->2, return 1->2.
7+ * Given 1->1->2->3->3, return 1->2->3.
8+ *
9+ */
10+
11+
12+ /**
13+ * Definition for singly-linked list.
14+ * function ListNode(val) {
15+ * this.val = val;
16+ * this.next = null;
17+ * }
18+ */
19+
20+ /**
21+ * @param {ListNode } head
22+ * @return {ListNode }
23+ */
24+ var deleteDuplicates = function ( head ) {
25+
26+ var p = head ;
27+ if ( ! p ) return p ;
28+ var all = [ p . val ] ;
29+ var t = p . next ;
30+
31+ while ( t ) {
32+
33+ if ( all . indexOf ( t . val ) == - 1 ) {
34+ all . push ( t . val ) ;
35+ p = t ;
36+ t = p . next ;
37+ } else {
38+ t = t . next ;
39+ p . next = t ;
40+ }
41+ }
42+ return head ;
43+
44+ } ;
45+
46+ /**
47+ * 改进方案
48+ *
49+ * @param {ListNode } head
50+ * @return {ListNode }
51+ */
52+ var deleteDuplicates2 = function ( head ) {
53+
54+ var p = head ;
55+ while ( p && p . next ) {
56+ if ( p . val == p . next . val ) {
57+ p . next = p . next . next ;
58+ } else {
59+ p = p . next ;
60+ }
61+ }
62+ return head ;
63+
64+ } ;
65+
66+
67+
You can’t perform that action at this time.
0 commit comments