welcome to my blog
程序员代码面试指南第二版 25.在链表中删除指定值的节点
题目描述
给出一个链表和一个整数 num,输出删除链表中节点值等于 num 的节点之后的链表。
输入描述:
第一行一个整数 n,n 表示单链表的节点数量。
第二行 n 个整数表示单链表的各个节点的值。
第三行一个整数 num。
输出描述:
在给定的函数中返回指定链表的头指针。
示例1
输入
4
1 2 3 4
3
输出
1 2 4
第一次做; 主要是维护好left指针; 代码细节: 创建临时节点后, 将临时节点连向head, 我连着两次忘记连head了!!
- 时间复杂度O(n)
- 空间复杂度O(1)
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
//input check
if(n<1)
return;
String[] str = sc.nextLine().split(" ");
int num = Integer.parseInt(sc.nextLine().trim());
//创建链表
ListNode head = new ListNode(Integer.parseInt(str[0]));
ListNode curr = head;
for(int i=1; i<n; i++){
curr.next = new ListNode(Integer.parseInt(str[i]));
curr = curr.next;
}
//execute
ListNode temp = new ListNode(0);
temp.next = head;
ListNode left = temp;
curr = head;
while(curr!=null){
if(curr.val==num){
left.next = curr.next;
}
else{
left = curr;
}
curr = curr.next;
}
head = temp.next;
//打印结果
curr = head;
while(curr!=null){
System.out.print(curr.val+" ");
curr = curr.next;
}
}
public static class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val = val;
}
}
}