1.3.24

question:

write a method removeafter() that takes a linked-list node as argument and removes the node following the given one(and does nothing if the argument or the next field in the argument node is null)

answer:

import edu.princeton.cs.algs4.*;

public class Linklist
{
    private static class Node//节点
    {
        String item;
        Node next = null;
    }
    
     public Node create(int n)//创建链表
    {
        Node head = null;
        Node p1 = head;
        Node p2;
        for(int i = 0; i < n; i++)
        {
            p2 = new Node();
            StdOut.println("input the string of node " + i + ":");
            p2.item = StdIn.readString();
            if(head == null)
            {
               head = p1 = p2;
            }
            else
            {
               p1.next = p2;
               p1 = p2;
            }
        }
        p1.next = null;
        return head;
    }
   
    public void show(Node head)//遍历链表
    {
        Node current = head;
        while(current != null)
        {
            StdOut.print(current.item + "\t");
            current= current.next;
        }
        StdOut.print("\n");
    }
    
    public boolean removeafter(Node current)
    {
        if(current.next == null || current == null)
        {
            return false;
        }
        Node after_current = current.next;//after_current就是要删除的node
        current.next = after_current.next;//删除
        return true;
    }
    
    public static void main(String[] args)
    {
        Node head;
        int n;
        Linklist linklist = new Linklist();
        StdOut.println("input the length of linklist:(>0)");
        n = StdIn.readInt();
        head = linklist.create(n);
        linklist.show(head);
        StdOut.println("input the c to delete the (c+1)th node:");//从第0个开始
        int c = StdIn.readInt();
        Node current = head;
        while(c>0)
        {
            current = current.next;
            c--;
        }
        boolean t = linklist.removeafter(current);
        if(t == true)
        {
            StdOut.println("delete");
        }
        else
        {
            StdOut.println("not delete");
        }
        linklist.show(head);
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9060002.html