描述
给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。
java代码
/**
* 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
if(head == null) return head;
ListNode node = head;
while(node.next != null) {
if(node.next.val == val) {
if(node.next.next != null) {
node.next = node.next.next;
}else {
node.next = null;
break;
}
} else {
node = node.next;
}
}
// 如果像 1->1->null val = 1 这样的,最后得到的是 1->null, 所以要把头部删除
if(head.val == val) return head.next;
return head;
}
}