首页 > 其他 > 详细

Remove Linked List Elements

时间:2015-05-05 01:13:20      阅读:288      评论:0      收藏:0      [点我收藏+]

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 }

 

Remove Linked List Elements

原文:http://www.cnblogs.com/qq1029579233/p/4478026.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!