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;
    }
}

 

posted on 2017-02-21 16:06  贝拉拉  阅读(634)  评论(0编辑  收藏  举报

导航