206. Reverse Linked List

可以用数组保存 然后每一个结点的值进行更改

https://www.bilibili.com/video/av49696612/?redirectFrom=h5

/**
 * 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 a = head;
    ListNode b = head.next;
    while(b!=null) {                                                        //不用去判断a
        ListNode c = b.next;
        b.next = a;
        a = b ;
        b = c ;
    }
    head.next = null;
    return a;                                                                    //记得返回a
    }
}

迭代法

public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    ListNode curr = head;
    while (curr != null) {
        ListNode nextTemp = curr.next;
        curr.next = prev;
        prev = curr;
        curr = nextTemp;
    }
    return prev;
}

递归

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return p;
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务