Skip to content

Latest commit

 

History

History
54 lines (40 loc) · 897 Bytes

Ex_1_3_25.md

File metadata and controls

54 lines (40 loc) · 897 Bytes
title date draft tags categories
Algorithm4 Java Solution 1.3.25
2019-07-04 05:47:10 +0800
false
JAVA
TECH
archives

1.3.25

Problem:

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).

Solution:

  public static void insertAfter(Node cur, Node x){
    if(cur==null || x==null){
      return;
    }
    x.next = cur.next;
    cur.next = x;
  }
public static void main(String[] args) {
    Node<String> a = new Node("a");
    a.append("c").append("d");
    StdOut.println("before insert:");
    print(a);
    Node<String> b = new Node<>("b");
    insertAfter(a,b);
    StdOut.println("after insert:");
    print(a);

//    before insert:
//    a 	c 	d
//    after insert:
//    a 	b 	c 	d

  }

Reference: