描述
给出一个链表和一个整数 num,输出删除链表中节点值等于 num 的节点之后的链表。
示例
输入:
4 1 2 3 4 3
输出:
1 2 4
解决方案:
方法一:利用栈来存储与num不相同的值,再取出拼接成新链表。时间复杂度O(n) 额外空间复杂度O(n)
方法二:不需要其它容器存储。利用pre与cur来改变节点地址。cur.value==num的话,就让pre指向cur.next ,否则就更新pre到变成当前cur,cur每次下移一个节点。时间复杂度O(n) 额外空间复杂度O(1)
import java.util.Scanner;
import java.util.Stack;
class Node{
public int value;
public Node next;
public Node(int value){
this.value=value;
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
String[] n=in.nextLine().split(" ");
String[] num=in.nextLine().split(" ");
int m=Integer.parseInt(in.nextLine());
Node node=transForNode(num);
//Node nodeF=removeValue1(node,m);//方法1
Node nodeF=removeValue2(node,m);//方法2
show(nodeF);
}
//打印链表
public static void show(Node head){
while(head!=null){
System.out.print(head.value+" ");
head=head.next;
}
System.out.println();
}
//数组转链表
public static Node transForNode(String[] nums) {
Node head = new Node(Integer.parseInt(nums[0]));
Node cur = head;
for(int i = 1; i < nums.length; i++) {
cur.next = new Node(Integer.parseInt(nums[i]));
cur = cur.next;
}
return head;
}
//方法一:利用栈,时间复杂度O(n) 额外空间复杂度O(n)
public static Node removeValue1(Node head,int num){
Stack<Node> stack=new Stack<Node>();
//从链头开始压栈
while(head!=null){
if(head.value!=num){
stack.push(head);
}
head=head.next;
}
while(!stack.isEmpty()){
stack.peek().next=head;
head=stack.pop();
}
return head;
}
//方法二:不利于其它容器,时间复杂度O(n) 额外空间复杂度O(1)
public static Node removeValue2(Node head,int num){
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;
}
}