美文网首页
LeetCode 206. 反转链表

LeetCode 206. 反转链表

作者: 怀旧的艾克 | 来源:发表于2019-07-14 13:43 被阅读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;
    }
}

相关文章

网友评论

      本文标题:LeetCode 206. 反转链表

      本文链接:https://www.haomeiwen.com/subject/gpbbkctx.html