单链表反转 2种方法
- 空间换时间
- 时间换空间
package com.stan.work; public class Step1 { /** * 单链表反转 206 * 链表中环的检测 141 * 两个有序的链表合并 * 删除链表倒数第 n 个结点 * 求链表的中间结点 */ /** * 自定义链表 */ public static class MyLinkNode { int val; MyLinkNode next; MyLinkNode() { } MyLinkNode(int val) { this.val = val; } MyLinkNode(int val, MyLinkNode next) { this.val = val; this.next = next; } } public static void main(String[] args) { MyLinkNode head = new MyLinkNode(1); MyLinkNode node1 = new MyLinkNode(2); MyLinkNode node2 = new MyLinkNode(3); MyLinkNode node3 = new MyLinkNode(4); head.next = node1; node1.next = node2; node2.next = node3; MyLinkNode node = reverseList(head); while (node != null) { System.out.print(node.val + " "); node = node.next; } System.out.println(); } /** * 迭代翻转 * * @param head * @return */ public static MyLinkNode reverseList(MyLinkNode head) { MyLinkNode curr = head; MyLinkNode prev = null; while (curr != null) { // 先换指针位置 再换next值 MyLinkNode next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; } /** * 递归翻转 * * @param head * @return */ public static MyLinkNode reverseList1(MyLinkNode head) { //递归出口 if (head == null || head.next == null) { return head; } //先递后归 MyLinkNode p = reverseList1(head.next); head.next.next = head; head.next = null; return p; } public static void searchNode(MyLinkNode head) { if (head == null) { return; } while (head != null && head.next != null) { System.out.print(head.val); } } }