问题描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
思路
1. 迭代
public ListNode reverseList(ListNode head) {if (head == null || head.next == null) {return head;}ListNode curr = head; //待处理结点ListNode prev = null; //当前的头结点while (curr != null) {ListNode temp = curr.next;curr.next = prev;prev = curr;curr = temp;}return prev;}
2. 递归
主要原理:递归执行过程即向下查找,向上返回
向下查找:找到链表的末节点p
向上返回:向上返回p(p在向上返回的过程中指代的节点没变)
只是在向上返回的过程中,捎带着改变下相邻节点的指向关系,逻辑如下
head.next.next = head;head.next = null;
public ListNode reverseList(ListNode head) {//递归结束条件,链表为空或者只有一个节点if (head == null || head.next == null) {return head;}//递ListNode p = reverseList(head.next);//归head.next.next = head;head.next = null;return p;}
