您的位置:首页
LeetCode -- 删除链表中值为k的元素
2017-08-10 15:52
218 查看
本题目比較直接,一次遍历遇到匹配的元素直接删除(通过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] Remove Nth Node From End of List 删除链表开始的第n个元素
- leetcode-83. Remove Duplicates from Sorted List(删除有序链表中的重复元素)
- [LeetCode] Remove b3dc Linked List Elements 删除链表中的元素
- <LeetCode> 题112:删除排序链表中的重复元素
- LeetCode Remove Linked List Elements 删除链表元素
- [LeetCode]Merge Two Sorted Lists & Remove Duplicates from Sorted List 两个有序链表合并为一个&删除链表重复元素
- LeetCode从零单排之零分段——Delete Node in a Linked List(删除链表中的元素)
- Remove Nth Node From End of List 链表删除倒数第N个元素@LeetCode
- Leetcode Remove Nth Node From End of List 删除链表倒数第n个元素
- [LeetCode]83. Remove Duplicates from Sorted List(删除有序链表的重复元素 )
- leetcode(83)—— 删除已排序链表重复元素(Remove Duplicates from Sorted List)
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)
- LeetCode83. 删除排序链表中的重复元素
- (LeetCode)Remove Duplicates from Sorted List --- 链表中删除重复元素
- Leetcode Remove Duplicates from Sorted List II 删除链表中重复的元素II
- 【LeetCode-面试算法经典-Java实现】【082-Remove Duplicates from Sorted List II(排序链表中删除重复元素II)】
- LeetCode 83. 删除排序链表中的重复元素
- [Leetcode] Remove duplicates from sorted list 从已排序的链表中删除重复元素
- leetcode解题之203 # Remove Linked List Elements Java版(删除链表中的和val相等的元素)
- LeetCode -- 删除链表中值为k的元素