206.反转链表
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
- 链表中节点的数目范围是
[0, 5000]
-5000 <= Node.val <= 5000
**进阶:**链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
题解:
本题的思路是扫描一遍链表,使用pre,cur, next三个指针来解决。pre和cur分表表示两个节点的前后关系,需要让cur的下一个指向cur.next = pre
,再指向之前再用next将cur的下一个保存起来,方便下次扫描。
代码实现如下:
package com.offer;
import com.offer.leetcode.datastruct.ListNode;
import com.offer.leetcode.datastruct.ListNodeUtils;
public class _206反转链表 {
public static void main(String[] args) {
ListNode header = ListNodeUtils.createList(new int[]{1});
ListNodeUtils.printListNode(header);
ListNode tail = reverseList(header);
ListNodeUtils.printListNode(tail);
}
public static ListNode reverseList(ListNode head) {
if (head == null) return null;
if (head.next == null) return head;
ListNode pre = null;
ListNode cur = head;
ListNode next = cur.next;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}