标签:lse temp als 遍历 public [] nothing port input
question:
write a method insertafter() that takes two linked-list node arguments and inserts the second after the first on its list(and does nothing if either argument 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 void insertafter(Node head, Node first, Node second) { if(first == null || second == null) { return; } Node current = head; while(current != null)//原链表里找first节点 { if(current.equals(first))//找到后插入second节点 { Node temp = current.next; current.next = second; second.next = temp; } current = current.next; } return; } 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); Node second = new Node(); StdOut.println("input the string item of second node"); second.item = StdIn.readString(); second.next = null; StdOut.println("input the c to insert after cth node:");//即first,且从第0个开始 int c = StdIn.readInt(); Node first = head; while(c>0) { first = first.next; c--; } linklist.insertafter(head,first,second); linklist.show(head); } }
标签:lse temp als 遍历 public [] nothing port input
原文地址:https://www.cnblogs.com/w-j-c/p/9060076.html