zoukankan      html  css  js  c++  java
  • 单链表的节点内数据值的删除问题(携程网笔试题)

    问题描述:给定一个单链表,链表中存储的数据都为整数,给定一个整数x,将单链表中所有与x相等的元素删除。

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

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

     1 import java.util.*;
     2 class Node{                                                   //链表节点的结构
     3     int data;
     4     Node next=null;
     5 }
     6 
     7 public class Main {
     8     public static void createLinklist(Node head,int length){
     9         Scanner scan=new Scanner(System.in);
    10         Node p=head;
    11         for(int i=0;i<length;i++)                              //循环建立链表
    12         {
    13             Node node=new Node();
    14             int data=scan.nextInt();
    15             node.data=data;
    16             p.next=node;
    17             p=node;
    18         }
    19     }
    20     public static void printLinklist(Node head){              //递归打印链表
    21         if(head.next!=null){
    22             System.out.print(head.next.data+"->");
    23             printLinklist(head.next);
    24         }
    25     }
    26     public static void deleteNode(Node head,int x){           //删除链表中的值为x的节点
    27         Node p=head;
    28         head=head.next;
    29         while(head!=null )
    30         {
    31            
    32            if(head.data==x)                                   //如果节点里的数据的值等于x,则直接将该节点指向下一个节点的下一个节点
    33                p.next=head.next;
    34            else
    35               p=head;
    36               
    37            head=head.next;                                     
    38         }
    39     }
    40     public static void main(String[] args) {
    41         // TODO 自动生成的方法存根
    42         Scanner scan=new Scanner(System.in);
    43         Node head=new Node();
    44         System.out.print("请输入链表的长度:");
    45         int length=scan.nextInt();
    46         System.out.print("请输入链表的每个节点的值:");
    47         createLinklist(head,length);
    48         System.out.print("这个链表为:");
    49         printLinklist(head);
    50         System.out.println();
    51         System.out.print("输入要删除的节点的值:");
    52         int x=scan.nextInt();
    53         deleteNode(head,x);
    54         System.out.print("删除"+x+"后的链表为:");
    55         printLinklist(head);
    56     }
    57 
    58 }

    测试样例输出为:

    请输入链表的长度:6
    请输入链表的每个节点的值:1 2 3 4 2 4
    这个链表为:1->2->3->4->2->4->
    输入要删除的节点的值:2
    删除2后的链表为:1->3->4->4->

  • 相关阅读:
    BigDecimal 和NumberFormat及 获取总页数的应用
    格式化小数点和百分号 DecimalFormatter
    Vue 项目开发
    js 对象补充
    Vue 实例成员
    Vue 指令
    Vue 介绍
    Vue
    request-html
    Python 中的经典类新式类
  • 原文地址:https://www.cnblogs.com/guozhenqiang/p/5470934.html
Copyright © 2011-2022 走看看