栈和队列----在单链表中删除指定值的节点

在单链表中删除指定值的节点

  

  给定一个链表的头节点head和一个整数num,实现一个函数删除链表中值为num的所有节点。例如,链表为 1->2->3->4->null ,num 为3,删除后,链表变为 1->2->4->null。

  

 【解析】

  方法一:使用栈或者其他容器收集节点的方法,其时间复杂度是 O(N),空间复杂度是O(N)将值不等于num的节点用栈收集起来,收集完成后重新连接即可。最后将栈底的节点作为新的头节点返回。

  方法二:不使用任何容器,直接调整的方法,其时间复杂度是 O(N),空间复杂度是O(1)

  首先必须确保头节点的值不为null,确保头节点的值后,然后遍历后面的

  如果后面的值为num,则pre.next = cur.next

  如果后面的值不为num,则 pre = cur

  

package com.test;

import com.test.ListNode;

import java.util.Stack;

/**
 * Created by Demrystv.
 */
public class RemoveListNodeOfValue {


    /**
     * 方法一,使用栈或者其他容器收集节点的方法,其时间复杂度是 O(N),空间复杂度是O(N)
     */
    public ListNode removeValue1(ListNode head, int num) {
        Stack<ListNode> stack = new Stack<ListNode>();
        while (head != null) {
            if (head.val != num) {
                stack.push(head);
            }
            head = head.next;
        }
        while (!stack.isEmpty()) {
            stack.peek().next = head;
            head = stack.pop();
        }
        return head;
    }
    
    
    /**
     *方法二,不使用任何容器,直接调整的方法,其时间复杂度是 O(N),空间复杂度是O(1)
     */
    public ListNode removeValue2(ListNode head, int num){
        while (head != null){
            if (head.val != num){
                break;
            }
            head = head.next;
        }
        ListNode pre = head;
        ListNode cur = head;
        while (cur != null){
            if (cur.val == num){
                pre.next = cur.next;
            }else {
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }
    
    
}

 

posted @ 2018-07-23 08:58  Demrystv  阅读(1214)  评论(0编辑  收藏  举报