标签:input div lis list.sh reads 节点 \n ret item
question:
write a function that takes the first node in a linked list as argument and (destructively) reverses the list, returning the first node in the result.
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; } } if(head != null) { 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 Node reverse(Node head) { Node first = head.next; Node second = head; Node temp; second.next = null; while(first != null)//可以花图思考 { temp = first.next; first.next = second; second = first; first = temp; } return second;//到达边界时first变成了null,实际上second才是new_first } public static void main(String[] args) { Node old_head; int n; Linklist linklist = new Linklist(); StdOut.println("input the length of linklist:(>0)"); n = StdIn.readInt(); old_head = linklist.create(n); linklist.show(old_head); Node new_head = linklist.reverse(old_head); linklist.show(new_head); } }
法二:
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; } } if(head != null) { 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 Node reverse(Node head)//我也不是很明白递归 { if(head.next == null) return head; Node second = head.next; Node rest = reverse(second); second.next = head; head.next = null; return rest; } 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); head = linklist.reverse(head); linklist.show(head); } }
标签:input div lis list.sh reads 节点 \n ret item
原文地址:https://www.cnblogs.com/w-j-c/p/9060950.html