LeetCode -- 刪除連結串列中值為k的元素
阿新 • • 發佈:2019-02-18
本題目比較直接,一次遍歷遇到匹配的元素直接刪除(通過n.next = n.next.next)就可以了,只是需要考慮到:
1.首節點的情況
2.末節點的情況
1.首節點的情況
2.末節點的情況
以下為實現:
public ListNode RemoveElements(ListNode head, int val) { // null list if(head == null){ return null; } // constains only one node if(head.next == null && head.val == val){ return null; } //remove first nodes while(head.val == val){ if(head.next == null){ break; } head = head.next; } var tmp = head; // nodes in between while(head.next != null){ if(head.next.val == val){ head.next = head.next.next; } else{ head = head.next; } if(head.next == null){ break; } } // last node if(head.val == val){ return null; } // restore head node head = tmp; return head; }