剑指 Offer 18. 删除链表的节点

方法一 双指针

 1 /**
 2  * Definition for singly-linked list.
 3  * function ListNode(val) {
 4  *     this.val = val;
 5  *     this.next = null;
 6  * }
 7  */
 8 /**
 9  * @param {ListNode} head
10  * @param {number} val
11  * @return {ListNode}
12  */
13 var deleteNode = function(head, val) {
14     //两个指针,一个指向当前元素,一个指向前一个元素,当遇到target时改变链表
15     if(head.val == val) return head.next;
16     let pre = head, cur = head.next;
17     while(cur) {
18         if(cur.val == val) {
19             pre.next = cur.next;
20             return head;
21         }
22         cur = cur.next;
23         pre = pre.next;
24     }
25     return head;
26 };

方法二 单指针

 1 /**
 2  * Definition for singly-linked list.
 3  * function ListNode(val) {
 4  *     this.val = val;
 5  *     this.next = null;
 6  * }
 7  */
 8 /**
 9  * @param {ListNode} head
10  * @param {number} val
11  * @return {ListNode}
12  */
13 var deleteNode = function(head, val) {
14     if(head.val == val) return head.next;
15     let cur = head;
16     while(cur.next != null && cur.next.val != val) {
17         cur = cur.next;
18     }
19     if(cur.next != null) {
20         cur.next = cur.next.next;
21     }
22     return head;
23 };

 

posted @ 2021-09-21 00:40  雪之下。  阅读(24)  评论(0)    收藏  举报