206. 反转链表剑指 Offer 24. 反转链表

tech2022-10-22  98

难度:简单

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL

进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

 分析:

迭代的话,需要一个指针pre始终指向新的链表头,需要一个指针cur来进行遍历,需要一个指针temp来做个中间存储的指针,然后就可以了;

递归比较难理解,1-2-3-4-5的话,单链表,递归最先处理的肯定是5,5没什么操作空间,直接返回就可以了,然后往上是4,4现在指向5,要换成5指向4,就用4.next.next=4,意思就是4的后继(5)的后继是4,就调换过来了,然后现在4.next依然是5,这里循环指了,所以要处理一下,要把4.next置为null,切断连接;

代码:

/** * 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 pre = null; ListNode cur = head; while (cur != null){ ListNode temp = cur.next; cur.next = pre; pre = cur; cur = temp; } return pre; } //递归法 public ListNode reverseList2(ListNode head) { if (head == null || head.next == null) return head; ListNode p = reverseList(head.next); head.next.next = head; head.next = null; return p; } }

结果:

最新回复(0)