LeetCode 面试题24. 反转链表

时间:2020-05-22
本文章向大家介绍LeetCode 面试题24. 反转链表,主要包括LeetCode 面试题24. 反转链表使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

定义一个函数,输入一个链表的头节点

反转该链表并输出反转后链表的头节点。

题目链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->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) {
        
        ListNode pre = null;
        ListNode cur = head;
        //cur永远指向当前结点,pre永远在cur的前面,next永远在cur的后面
        while(cur != null){
            ListNode next = cur.next;  //next指向cur的下一个结点
            cur.next = pre;             //当前节点cur指向pre
            pre = cur;                  //pre往前走一步
            cur = next;                 //cur往前走一步
        }
        return pre;
    }
}

大家如果感兴趣可以前去手搓

本分类只用作个人记录,大佬轻喷.

原文地址:https://www.cnblogs.com/xiaofff/p/12938647.html