203.移除链表元素(力扣) Java实现

题目 

删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

原链表操作

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    //原链表操作
    public ListNode removeElements(ListNode head, int val) {
        ListNode cur = head;
        if(head==null){
            return null;
        }
        while(cur.next!=null){
            if(cur.next.val==val){         //从第二个节点开始判断是否需要删除,没有判断头节点
                cur.next = cur.next.next;  //若cur.next为需要删除的节点,则跳过该节点
            }else{
                cur = cur.next;
            }
        }
        if(head.val==val){               //判断头节点是否需要删除
                return head.next;
            }else{
                return head;
            }
    }
}

利用哨兵节点

class Solution {
    public ListNode removeElements(ListNode head, int val) {
      ListNode sentry = new ListNode(-1);    
      sentry.next = head;                   //引入哨兵节点,消除头节点的特殊性
      ListNode cur = sentry;
      while(cur.next!=null){
          if(cur.next.val==val){
              cur.next = cur.next.next;
          }else{
              cur = cur.next;
          }
      }
        return sentry.next;
    }
}

结果链表操作

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
    ListNode result = null;         //定义结果链表,同时是结果链表的头节点
    ListNode last = null;           //记录结果链表的尾节点
    ListNode cur = head;
    while(cur!=null){
        ListNode next = cur.next;   //记录当前节点的下一个节点
        if(cur.val!=val){
            cur.next = null;        //置空,节点从链表中分离出来,成为单个节点
                                    //置空一定要在记录下一个节点之后,防止引用丢失
            //尾插
            if(result==null){
                result = cur;             
            }else{
                last.next = cur;              
            }
            last = cur;
        }
        cur = next;
    }
    return result;
}
}

若不置空会出现错误:

输入:

[1,2,6,3,4,5,6] 6

输出

[1,2,3,4,5,6]

预期结果

[1,2,3,4,5]

将5尾插到结果链表后,5的下一个节点仍是6。

发布了91 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42006733/article/details/104302276