您的位置:首页 > 理论基础 > 数据结构算法

单链表的节点内数据值的删除问题(携程网笔试题)

2016-05-08 16:50 375 查看
问题描述:给定一个单链表,链表中存储的数据都为整数,给定一个整数x,将单链表中所有与x相等的元素删除。

              例如:单链表为(1,2,3,4,2,4),x=2,则删除节点后链表为(1,3,4,4)

分析:这是链表的基本操作问题,具体的Java代码如下:

import java.util.*;
class Node{ //链表节点的结构
int data;
Node next=null;
}

public class Main {
public static void createLinklist(Node head,int length){
Scanner scan=new Scanner(System.in);
Node p=head;
for(int i=0;i<length;i++) //循环建立链表
{
Node node=new Node();
int data=scan.nextInt();
node.data=data;
p.next=node;
p=node;
}
}
public static void printLinklist(Node head){ //递归打印链表
if(head.next!=null){
System.out.print(head.next.data+"->");
printLinklist(head.next);
}
}
public static void deleteNode(Node head,int x){ //删除链表中的值为x的节点
Node p=head;
head=head.next;
while(head!=null )
{

if(head.data==x) //如果节点里的数据的值等于x,则直接将该节点指向下一个节点的下一个节点
p.next=head.next;
else
p=head;

head=head.next;
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner scan=new Scanner(System.in);
Node head=new Node();
System.out.print("请输入链表的长度:");
int length=scan.nextInt();
System.out.print("请输入链表的每个节点的值:");
createLinklist(head,length);
System.out.print("这个链表为:");
printLinklist(head);
System.out.println();
System.out.print("输入要删除的节点的值:");
int x=scan.nextInt();
deleteNode(head,x);
System.out.print("删除"+x+"后的链表为:");
printLinklist(head);
}

}

测试样例输出为:

请输入链表的长度:6

请输入链表的每个节点的值:1 2 3 4 2 4

这个链表为:1->2->3->4->2->4->

输入要删除的节点的值:2

删除2后的链表为:1->3->4->4->
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息