LeetCode 剑指offer24——反转链表

题目链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

 

示例:

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

思路: 思路

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
public class Solution {
    public ListNode ReverseList(ListNode head) {
        //如果链表为空或一个节点则直接返回
        if(head == null || head.next == null){
            return head;
        }
        //定义前后两个指针pre,cur
        ListNode pre = null;
        ListNode next = null;
       while(head!=null){
           next = head.next;
           head.next = pre;
           pre = head;
           head = next;
       }
        //步骤4(head==null)
        return pre;
    }
}
end

评论