LeetCode 206. Reverse Linked List(链表)

题目来源:https://leetcode.com/problems/reverse-linked-list/

问题描述

206. Reverse Linked List

Easy

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL

Output: 5->4->3->2->1->NULL

------------------------------------------------------------

题意

单链表反转。

------------------------------------------------------------

思路

维护三个指针head, tmp, ptr,head指向当前节点,tmp指向原链表里当前节点的后继节点,ptr指向原链表里当前节点的前驱节点。顺序遍历原链表,每次将head.next指向ptr,但是原链表的头指针要指向null.

------------------------------------------------------------

代码

/**
 * 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 ptr = null, tmp = null;
        while (true)
        {
            tmp = head.next;
            if (ptr == null)
            {
                ptr = head;
                ptr.next = null;
            }
            else
            {
                head.next = ptr;
                ptr = head;
            }
            if (tmp == null)
            {
                return head;
            }
            head = tmp;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/88885068