LeetCode 206. 反转链表 [Hot 100]
简单
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
迭代法
class Solution {
public ListNode reverseList(ListNode head) {
ListNode head2 = new ListNode();
while (head != null) {
ListNode t = head.next;
head.next=head2.next;
head2.next=head;
head=t;
}
return head2.next;
}
}
递归法★
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
版权申明
本文系作者 @xiin 原创发布在To Future$站点。未经许可,禁止转载。
暂无评论数据