码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--Remove Linked List Element

时间:2015-05-18 12:48:32      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

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

    注意事项:while停止的条件要特备注意;各种输入情况都要考虑到;如果首节点就是要删除的节点肿么办,等等问题。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
         if(head == null)
              return null;
          if(head.next==null && head.val==val)
              return null;
          if(head.next==null && head.val!=val)
              return head;
          ListNode p = head;
          
          while(head.next!=null && head.val==val){
              p = head;
              head = head.next;
              p.next = null;
          }
          
          p = head;
          ListNode q = p.next;
          while(p.next!=null){
              q = p.next;
              if(q.val == val){
                  p.next = q.next;
                  q.next = null;
              }
              else{
                  p = q;
                  q = p.next;
              }
          }
          if(head.val==val)//做最后的检查,看是否首节点是要删除的元素
              return null;
          return head;
         
    }
}

 

LeetCode--Remove Linked List Element

标签:

原文地址:http://www.cnblogs.com/little-YTMM/p/4511473.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!