码迷,mamicode.com
首页 > 其他好文 > 详细

1.3.24

时间:2018-05-19 14:02:53      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:oid   color   void   reads   lse   public   head   input   []   

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

 

1.3.24

标签:oid   color   void   reads   lse   public   head   input   []   

原文地址:https://www.cnblogs.com/w-j-c/p/9060002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!