题目链接
给你单链表的头节点 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
双指针
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/class Solution {public ListNode reverseList(ListNode head) {ListNode pre = null;ListNode current = head;ListNode temp = null;while (current != null){temp = current.next;current.next = pre;pre = current;current = temp;}return pre;}}
递归
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { return reverse(null, head); } public ListNode reverse(ListNode prev, ListNode cur) { // 递归终止条件,在当前指向null时 // 空链表 head=null 或者是 已经翻转完最后一个元素 if(cur == null) { return prev; } ListNode temp = cur.next; //保存下一个节点 cur.next = prev; // 翻转当前节点 return reverse(cur, temp); // 相当于双指针的 pre = current; current = temp; } }
