LinkedList - 206. Reverse Linked List

时间:2022-07-25
本文章向大家介绍LinkedList - 206. Reverse Linked List,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
  1. 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?

思路:

翻转链表,本来不想记录了,但是是链表系列中的“hello world”,有纪念意义,主要有两种方法,迭代和递归。 注意不要断链。

代码:

java:

/**

 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    // iterative
   /* public ListNode reverseList(ListNode head) {
        if (head == null) return head;
        
        ListNode curr = head;
        ListNode prev = null;
        
        while (curr != null) {
            ListNode temp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = temp;
        }
        
        return prev;
    }*/
    
  
    // recursive 
    public ListNode reverseList(ListNode head) {
        return reverseListInt(head, null);
    }

    private ListNode reverseListInt(ListNode head, ListNode newHead) {
        if (head == null)
            return newHead;
        ListNode next = head.next;
        head.next = newHead;
        return reverseListInt(next, head);
    }
}```