将单链表的链接顺序反转过来
- 例:输入:1->2->3->4->5
- 输出:5->4->3->2->1
使用两种方式解题
1 迭代
static class ListNode {int val;ListNode next;public ListNode(int val, ListNode next) {this.val = val;this.next = next;}
}public static ListNode reverseList(ListNode head) {if (head == null || head.next == null) {return head;}ListNode pre = null, cur = head, next;while (cur != null) {// 保存下一个节点next = cur.next;// 反转链表cur.next = pre;pre = cur;cur = next;}return pre;
}public static void main(String[] args) {ListNode node5 = new ListNode(5, null);ListNode node4 = new ListNode(4, node5);ListNode node3 = new ListNode(3, node4);ListNode node2 = new ListNode(2, node3);ListNode node1 = new ListNode(1, node2);reverseList(node1)
}
2 递归
public static ListNode recursion(ListNode head) {if (head == null || head.next == null) {return head;}ListNode newHead = recursion(head.next);head.next.next = head;head.next = null;return newHead;
}