关闭

LeetCode 206 Reverse Linked List (逆置链表)

标签: leetcode
480人阅读 评论(0) 收藏 举报
分类:

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;
    }
}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:574662次
    • 积分:13504
    • 等级:
    • 排名:第954名
    • 原创:802篇
    • 转载:7篇
    • 译文:0篇
    • 评论:119条
    博客专栏