🎯 请点击上方原题链接,查看题目描述👆
💭 解题思路#
递归#
方法的意思是反转链表,我们直接反转head.next。然后再把head做一下反转即可。
class Solution { public ListNode reverseList(ListNode head) { //base case 如果节点为空节点,或者单节点,直接返回即可,不用反转 if (head == null || head.next == null)return head;
//反转 ListNode temp = reverseList(head.next); //反转head head.next.next = head; head.next = null; return temp; }}
迭代#
class Solution { public ListNode reverseList(ListNode head) { ListNode cur = head,pre = null; while(cur != null){ ListNode temp = cur.next; cur.next = pre; pre = cur; cur = temp; } return pre; }}