题目:在单链表中删除指定值的节点
方法一:利用一个栈结构。
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;
}
}
参考资料:《程序员面试代码指南》左程云 著