首页 > 其他 > 详细

LeetCode--Remove Linked List Element

时间:2015-05-18 12:47:31      阅读:159      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!