1. 程式人生 > >1.3.24

1.3.24

follow print true eth stdout stat bsp public AR

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