题目描述
输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。
详细描述:
本题为考察链表的插入和删除知识。
链表的值不能重复
构造过程,例如
1 <- 2
3 <- 2
5 <- 1
4 <- 5
7 <- 2
最后的链表的顺序为 2 7 3 1 5 4
删除 结点 2
则结果为 7 3 1 5 4
输入描述:
1 输入链表结点个数
2 输入头结点的值
3 按照格式插入各个结点
4 输入要删除的结点的值
输出描述:
输出删除结点后的序列,每个数后都要加空格
示例1
输入
复制
5
2
3 2
4 3
5 2
1 4
3
输出
复制
2 5 4 1
解题步骤:
1.定义Node类
class Node{
int val;
Node next;
Node(int val){
this.val=val;
}
}
2.插入方法insert
//pHead头结点,preVal上一节点值,nextVal插入节点值
public static void insert(Node pHead,int preVal,int nextVal){
Node pNext=new Node(nextVal);
Node pCurrent=pHead;
while(pCurrent!=null){
if(pCurrent.val == preVal)
{
pNext.next = pCurrent.next;
pCurrent.next = pNext;
break;
}
pCurrent = pCurrent.next;
}
}
3.删除节点方法removeNode:
public static Node removeNode(Node pHead,int val)
{
Stack<Node> stack = new Stack<Node>();
while(pHead != null)
{
if(pHead.val != val)
{
stack.push(pHead);
}
pHead = pHead.next;
}
while(!stack.isEmpty())
{
stack.peek().next = pHead;
pHead = stack.pop();
}
return pHead;
}
4.main方法调用上述
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
//输入节点数
int nodeNum=sc.nextInt();
//输入头结点的值
int headVal=sc.nextInt();
//构造头结点
Node pHead=new Node(headVal);
for(int i=0;i<nodeNum-1;i++){
//插入节点值
int nextVal=sc.nextInt();
//前一节点值
int preVal=sc.nextInt();
insert(pHead,preVal,nextVal);
}
int deleteVal=sc.nextInt();
pHead = removeNode(pHead, deleteVal);
while(pHead.next != null)
{
System.out.print(pHead.val + " ");
pHead = pHead.next;
}
System.out.println(pHead.val + " ");
}
}
——————————————————————————————————
整体代码:
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
//输入节点数
int nodeNum=sc.nextInt();
//输入头结点的值
int headVal=sc.nextInt();
//构造头结点
Node pHead=new Node(headVal);
for(int i=0;i<nodeNum-1;i++){
//插入节点值
int nextVal=sc.nextInt();
//前一节点值
int preVal=sc.nextInt();
insert(pHead,preVal,nextVal);
}
int deleteVal=sc.nextInt();
pHead = removeNode(pHead, deleteVal);
while(pHead.next != null)
{
System.out.print(pHead.val + " ");
pHead = pHead.next;
}
System.out.println(pHead.val + " ");
}
}
//pHead头结点,preVal上一节点值,nextVal插入节点值
public static void insert(Node pHead,int preVal,int nextVal){
Node pNext=new Node(nextVal);
Node pCurrent=pHead;
while(pCurrent!=null){
if(pCurrent.val == preVal)
{
pNext.next = pCurrent.next;
pCurrent.next = pNext;
break;
}
pCurrent = pCurrent.next;
}
}
public static Node removeNode(Node pHead,int val)
{
Stack<Node> stack = new Stack<Node>();
while(pHead != null)
{
if(pHead.val != val)
{
stack.push(pHead);
}
pHead = pHead.next;
}
while(!stack.isEmpty())
{
stack.peek().next = pHead;
pHead = stack.pop();
}
return pHead;
}
}
class Node{
int val;
Node next;
Node(int val){
this.val=val;
}
}