Tc的专栏

待重头,收拾旧山河,朝天阙

LeetCode 206 Reverse Linked List (逆置链表)

Reverse a singly linked list.


Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?


题目链接:https://leetcode.com/problems/reverse-linked-list/

题目分析:链表的逆置,迭代和递归分别实现

迭代法:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null) {
            return head;
        }
        ListNode cur = head.next;
        head.next = null;
        while(cur != null) {
            ListNode tmp = cur.next;
            cur.next = head;
            head = cur;
            cur = tmp;
        }
        return head;
    }
}

递归法:所谓递归,就当有个栈在维护

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode Rhead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return Rhead;
    }
}



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/52355883
文章标签: leetcode
个人分类: Leetcode Easy
所属专栏: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode 206 Reverse Linked List (逆置链表)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭