1 题目
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2 Java
2.1 !方法一(递归,原地反转)
返回已反转过来的链表的第一个节点
例如,5–>4–>3–>2–>1
reverseList(3.next)返回的是,3之后 已经反转过来的链表的第一个节点,即1,图解就是
5–>4–>3,null<–2<–1
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
// 只能遍历到最后一个节点,不能遍历到null
if(head == null || head.next == null) return head;
// reverseList所有递归方法的返回值都是同一个tail
ListNode tail = reverseList(head.next);
// 处理过程:将当前节点和后一个节点关系翻转
head.next.next = head;
head.next = null; // 这一步是为了第一个节点,在翻转后能指向null
return tail;
}
}
这个返回值不太好理解,换种写法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
helper(head);
return tail;
}
ListNode tail = null;
public void helper(ListNode head){
// 遍历到最后一个节点,记录到成员变量
if(head == null || head.next == null){
tail = head;
return;
}
// 先翻转后面的节点,再翻转当前节点
helper(head.next);
// 处理过程:将当前节点和后一个节点关系翻转
head.next.next = head;
head.next = null; // 这一步是为了第一个节点,在翻转后能指向null
}
}
2.2 方法二(递归,反转至新链表)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
helper(head);
return reverseHead;
}
ListNode reverseHead = null;
ListNode reverseTail = null;
public void helper(ListNode head){
if(head == null){
return;
}else if(head.next == null){ // 递归到最后一个节点,记录到成员变量
reverseHead = new ListNode(head.val);
reverseTail = reverseHead;
return;
}
// 先递归到底
helper(head.next);
// 将当前节点挂到reverseHead尾部
reverseTail.next = new ListNode(head.val);
reverseTail = reverseTail.next;
}
}
2.3 方法三(迭代,原地反转)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode pre = head;
ListNode cur = head.next;
pre.next = null;
while(cur != null){
ListNode post = cur.next;
cur.next = pre; // 核心
pre = cur;
cur = post;
}
return pre;
}
}
2.4 方法四(迭代,反转至新链表,头插式)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode headNew = new ListNode(0);
while(cur != null){
ListNode node = new ListNode(cur.val); // 相当于在链表headNew的序号2(从1开始)插入新节点
node.next = headNew.next;
headNew.next = node;
cur = cur.next;
}
return headNew.next;
}
}