码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 206 链表 Reverse Linked List

时间:2020-03-02 00:53:59      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:ever   end   ==   html   sans   ble   fun   data   链表   

LeetCode 206 链表 Reverse Linked List

Reverse a singly linked list.
Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

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

代码:
iteratively

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

recursively

public ListNode reverseList(ListNode head) {
    return reverse(null,head);
}

private static ListNode reverse(ListNode pre,ListNode cur){
    if(cur==null) return pre;
    ListNode next = cur.next;
    cur.next = pre;
    return reverse(cur,next);
}

注意:
不要创建新节点

LeetCode 206 链表 Reverse Linked List

标签:ever   end   ==   html   sans   ble   fun   data   链表   

原文地址:https://www.cnblogs.com/muche-moqi/p/12393036.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!