Reverse a singly linked list.

click to show more hints.

Hint:

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

分析

想翻转一个linkedlist,涉及到current node的prev,next,所以对于每个node的翻转,要有前,中,后三个node参与

/**
 * 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 prev = null;
    ListNode curr = head;
    while (curr != null) {
        ListNode nextTemp = curr.next;
        curr.next = prev;
        prev = curr;
        curr = nextTemp;
    }
    return prev;

}

recursive

public class Solution {
    public ListNode reverseList(ListNode head) {

        if(head == null || head.next == null){
            return head;
        }

        ListNode next = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return next;

    }

}

results matching ""

    No results matching ""