206. Reverse Linked List

来源:互联网 发布:微信砸金蛋源码 编辑:程序博客网 时间:2024/04/29 12:23

链表基础题,经典题。

Reverse a singly linked list.

之前报错是因为返回了head。但是跳出循环的时候head就已经是null的了,所以要返回pre。


/**

 * 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) {
        ListNode pre = null;
       // ListNode cur = head;
        while (head != null) {
            ListNode temp = head.next;
            head.next = pre;
            pre = head;
            head = temp;
        }
        return pre;
    }
}
0 0
原创粉丝点击