《程序员代码面试指南》在单链表中删除指定值的节点

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

 

方法一:利用一个栈结构。


 

class Node{

            Integer value;

            public Node next;

            

            public Node(Integer data){

                  this .value = data;

            }

      }

      public Node deleteNode(Node head, Integer num){

            Stack<Node> s = new Stack<Node>();

            if(head == null){

                  return head;

            }

            while(head != null){

                  if(head.value != num){

                        s.push(head);

                  }

                  head = head.next; 

            }

            while(!s.isEmpty()){

                  s.peek().next = head;

                  head = s.pop();

            }

            return head;

            

      }

方法二:不需要任何容器直接进行操作

首先从头节点开始,找到第一个值不等于 num 的节点,作为新的头节点,这个节点是肯定不用删除的,记作 newHead。继续往后遍历,假设当前节点为 cur ,如果 cur 的值为 num 就将 cur 的值删除,删除的方式是将之前最近一个值不等于 num 的节点 pre 连接到 cur 的下一个节点,即 pre.next = cur.next ; 如果 cur 节点值不等于 num , 就令 pre = cur,即更新最近一个不为 num 的节点。

public class Node{

            public Integer value;

            public Node next;

            public Node(Integer data){

                  this.value = data;

            }

            public Node removeNode(Node head, Integer num){

                  if(head == null){

                        return head;

                  }

                  while(head != null){

                        if(head.value != num){

                              break;

                        }

                        head = head.next;

                  }

                  Node pre = head;

                  Node cur = head;

                  while(cur != null){

                        if(cur.value == num){

                              pre.next = cur.next;

                        }else{

                              pre = cur;

                        }

                        cur = cur.next;

                  }

                  return head;

            }

      }

参考资料:《程序员面试代码指南》左程云 著

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值