题目描述
输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。
链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
详细描述:
本题为考察链表的插入和删除知识。
链表的值不能重复
构造过程,例如
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 输入要删除的结点的值
输出描述:
输出删除结点后的序列
import java.util.*;
public class Main6{
public static void main(String[] args){
// Scanner scan=new Scanner(System.in);
// while(scan.hasNext()){
// int num=scan.nextInt();
// int headVal=scan.nextInt();
// scan.nextLine();
// ArrayList<String> list=new ArrayList<>();
// for(int i=0; i<num-1; i++){
// list.add(scan.nextLine());
// }
// int de=scan.nextInt();
// ListNode head=new ListNode(headVal);
// ListNode pt;
// for(String str: list){
// pt=head;
// ListNode p=new ListNode(str.charAt(0)-'0');
// while(pt.val!=(str.charAt(2)-'0')){
// pt=pt.next;
// }
// p.next=pt.next;
// pt.next=p;
// }
//
// pt=head;
// while(pt!=null){
// if(head.val==de){
// head=head.next;
// break;
// }
// if(pt.next.val==de){
// pt.next=pt.next.next;
// break;
// }
// else{
// pt=pt.next;
// }
// }
// pt=head;
// while(pt!=null){
// if(pt.next==null){
// System.out.println(pt.val);
// }
// else{
// System.out.print(pt.val+" ");
// }
// pt=pt.next;
// }
// }
@SuppressWarnings("resource")
Scanner scan=new Scanner(System.in);
while(scan.hasNext()){
int num=scan.nextInt();
int headVal=scan.nextInt();
LinkedList<Integer> list=new LinkedList<>();
list.add(0, headVal);
for(int i=0; i<num-1; i++){
int value=scan.nextInt();
int index=scan.nextInt();
list.add(list.indexOf(index)+1, value);
}
int de=scan.nextInt();
list.remove(list.indexOf(de));
for(int s: list){
System.out.print(s+" ");
}
System.out.println();
}
}
}
//class ListNode {
// public int val;
// public ListNode next;
// public ListNode(int val){
// this.val=val;
// this.next=null;
// }
//}

565

被折叠的 条评论
为什么被折叠?



