zoukankan      html  css  js  c++  java
  • java笔试之从单向链表中删除指定值的节点

    输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。

    链表的值不能重复

    构造过程,例如

    1 -> 2

    3 -> 2

    5 -> 1

    4 -> 5

    7 -> 2

    最后的链表的顺序为 2 7 3 1 5 4 

    删除 结点 2 

    则结果为 7 3 1 5 4 

    package test;
    
    import java.util.Scanner;
    
    class ListNode {
        int value;
        ListNode next = null;
    
        public ListNode() {
        }
    
        public ListNode(int value) {
            this.value = value;
        }
    }
    
    public class exam24 {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int count,hvalue,indata,deldata,pos;
            StringBuffer sBuffer=new StringBuffer();
            while (scanner.hasNext()) {
                count=scanner.nextInt();//结点个数
                hvalue=scanner.nextInt();//头节点值
                ListNode head=new ListNode(hvalue);
                
                //创建单向链表
                for (int i = 1; i < count; i++) {
                    indata=scanner.nextInt();
                    pos=scanner.nextInt();
                    Insert(head, indata, pos);
                }
                
                //删除值为deldata的结点
                deldata=scanner.nextInt();
                Delete(head, deldata);
                
                ListNode lNode=head;
                //开始遍历
                while(lNode!=null){
                    sBuffer.append(Integer.toString(lNode.value)+" ");
                    lNode=lNode.next;
                }
                System.out.println(sBuffer.substring(0,sBuffer.length()));
                sBuffer.delete(0, sBuffer.length());
    
            }
            scanner.close();
        }
    
        // 采用头插法
        public static void Insert(ListNode head, int value, int pos) {
            ListNode preNode = head;
            while (preNode.value!=pos) {
                preNode=preNode.next;
            }
            ListNode pNode=new ListNode(value);
            pNode.next=preNode.next;
            preNode.next=pNode;
        }
        
        public static void Delete(ListNode head,int pos){
            ListNode preNode=head;
            while(preNode.next.value!=pos)
                preNode=preNode.next;
            preNode.next=preNode.next.next;
        }
    }
  • 相关阅读:
    ftrace 使用方法
    在Ubuntu custom kernel上裝perf by compile
    [fw]How to use DISM to install a hotfix from within Windows
    Ubuntu下配置了ssh,但是连接很慢
    Fix invisible cursor issue in Ubuntu 13.10
    超強的Linux指令解釋網站《explainshell.com》,學Linux必備!
    python 读取 log日志的编码问题
    随机森林random forest及python实现
    评分卡系列(三):分类学习器的评估
    评分卡系列(二):特征工程
  • 原文地址:https://www.cnblogs.com/bella-young/p/6424590.html
Copyright © 2011-2022 走看看