題目:
刪除鏈表中等于給定值val的所有節(jié)點(diǎn)。
樣例
給出鏈表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回刪除3之后的鏈表:1->2->4->5壳炎。
Remove all elements from a linked list of integers that have value val.
Example
Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5
解答:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @param val an integer
* @return a ListNode
*/
public ListNode removeElements(ListNode head, int val) {
// Write your code here
//如果是空表直接返回null
if(head == null) return head;
ListNode p = head,q = head.next;
//遍歷整條鏈表
while(q != null){
//如果節(jié)點(diǎn)符合條件則刪除僻弹,并把刪除節(jié)點(diǎn)前后的節(jié)點(diǎn)連接
if(q.val == val){
p.next = q.next;
q = q.next;
}else{
p = p.next;
q = q.next;
}
}
//如果第一個就滿足直接刪除
if(head.val == val) head = head.next;
return head;
}
}