反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
package p206; /** * Created by admin on 2019/1/10. */ public class Main { public static class Node{ public int value; public Node next; public Node(int data){ this.value = data; } } public static void main(String[] args) { Node node1 = new Node(1); Node node2 = new Node(2); Node node3 = new Node(3); Node node4 = new Node(4); Node node5 = new Node(5); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; node5.next = null; Main m = new Main(); Node node = m.reverseList2(node1); Node current = node; System.out.println(current.value); } public Node reverseList(Node head){ Node pre = null; Node next = null; while (head != null) { next = head.next; head.next = null; pre = head; head = next; } return pre; } public Node reverseList2(Node head){ if (head == null || head.next == null) { return head; } Node pre = null; while (head != null) { Node temp = head.next; head.next = pre; pre = head; head = temp; } return pre; } }