LeetCode -- 刪除鏈表中值為k的元素
阿新 • • 發佈:2017-08-10
lis lee des != remove element 能夠 art ons
本題目比較直接,一次遍歷遇到匹配的元素直接刪除(通過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; }
LeetCode -- 刪除鏈表中值為k的元素