Remove Linked List Elements

https://leetcode.com/problems/remove-linked-list-elements/

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

 

 1 public class Solution {
 2     public static ListNode removeElements(ListNode head, int val) {
 3     while(head!=null&&head.val==val){head=head.next;}
 4     if(head==null){return null;}
 5     ListNode pre_li=head;
 6     ListNode li=head.next;
 7     while(li!=null){
 8         if(li.val==val){pre_li.next=li.next;li=li.next;}
 9         else{pre_li=li;li=li.next;}
10     }
11     return head;
12     }
13     public static class ListNode {
14     int val;
15     ListNode next;
16 
17     ListNode(int x) {
18         val = x;
19     }
20     }
21     public static void main(String[]args){
22     ListNode[]node=new ListNode[4];
23     for(int i=0;i<node.length;i++){
24         node[i]=new ListNode(1);
25     }
26     node[0].next=node[1];
27     node[1].next=node[2];
28     node[2].next=node[3];
29     ListNode head=removeElements(node[0],1);
30     while(head!=null){
31         System.out.println(head.val);
32         head=head.next;
33     }
34     }
35 }

 

posted @ 2015-05-04 23:42  打小孩  阅读(135)  评论(0编辑  收藏  举报