LeetCode 206. 反转链表

2019-07-14  本文已影响0人  怀旧的艾克

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

题解

java代码如下

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode new_head = new ListNode(0);
        ListNode ptr = head;
        
        while(head != null) {
            ptr = head.next;
            head.next = new_head.next;
            new_head.next = head;
            head = ptr;
        }
        
        return new_head.next;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读