LeetCode 203. Remove Linked List Elements

来源:互联网 发布:齐鲁软件大赛奖金 编辑:程序博客网 时间:2024/06/01 08:35

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5


public class Solution {    public ListNode removeElements(ListNode head, int val) {        if(head==null){     //head为空的情况            return head;        }        while(head!=null && head.val==val){               head=head.next;        }        if(head==null){     //head不为空,但是所有链表前面的说有值都等于val            return head;        }else{                          ListNode p=head;            ListNode q=head.next;            while(q!=null){                if(q.val==val){                    p.next=q.next;                    q=p.next;                }else{                    p=q;                    q=q.next;                }            }        }        return head;    }}

0 0
原创粉丝点击