LeetCode第206题

LeetCode第206题:反转链表

题目详述

反转一个链表

解法一

迭代。需要两个临时指针一个指向前驱一个指向后继

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while(curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }
}

解法二

递归。

class Solution {
    public ListNode reverseList(ListNode head) {
    	//若只有一个节点,可防止其出现循环
        if(head == null || head.next == null) return head;
        ListNode p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
}
发布了40 篇原创文章 · 获赞 0 · 访问量 661

猜你喜欢

转载自blog.csdn.net/weixin_42610002/article/details/104100497