203. Remove Linked List Elements
原题链接:https://leetcode.com/problems/remove-linked-list-elements/description/
实现如下:
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
// System.out.println(s.removeElements());
}
/**
* 这道题目应该就是考察链表的操作啦,没啥难点,值得一提的是:我这个实现需要先处理下链表的头部部分,但是有位高手提交的答案是在头部结点
* 前面加上一个冗余结点,然后头部结点就可以和其他结点一样就行正常的遍历啦!!!
*
* @param head
* @param val
* @return
*/
public ListNode removeElements(ListNode head, int val) {
ListNode prev = head, curr = head;
while (curr != null && curr.val == val) {
curr = curr.next;
}
if (curr == null) {
return null;
}
ListNode res = curr;
prev = curr;
while (curr != null) {
if (curr.val == val) {
prev.next = curr.next;
curr = curr.next;
} else {
prev = curr;
curr = curr.next;
}
}
return res;
}
}