题目描述:定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
解决方法1:双指针+循环
定义cur结点,用来指向当前结点的下一个结点。
定义pre结点,用来作为新的链表的下一个结点。
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null) return head;
ListNode pre = null;
while(head != null){
ListNode cur = head.next;
head.next = pre;
pre = head;
head = cur;
}
return pre;
}
}
解决方法2:递归
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null) return head;
return reverse(head);
}
public ListNode reverse(ListNode cur) {
if (cur.next == null) return cur; // 原链表的尾节点作为已反转链表的头节点,往回传递
ListNode nxt = reverse(cur.next); // 获得已反转链表的头节点
cur.next.next = cur; // 使cur的后继(已反转链表的尾节点)指向cur
cur.next = null; // 此时cur成为了已反转链表的尾节点,使cur指向null
return nxt; // 往回传递已反转链表的头节点
}
}