【刷leetcode】14.反转链表

题目描述

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

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

限制:
0 <= 节点个数 <= 5000

思路

想要反转链表,就得把链表里所有元素的next进行修改。
这里我们新设置两个相邻的双指针。
firstnode初始指向null,nextnode初始指向头节点head。
当nextnode不为空时,就可以修改nextnode的指针啦!
修改指针前,应先记录下nextnode的下一个节点temp,不然后面就找不到了。
把nextnode的next修改成firstnode
修改好指针后,再把firstnode和nextnode一起向后移动:firstnode指向nextnode指的,nextnode指向temp
直到nextnode为空,此时firstnode指向了尾节点。整个链表就得到了反转!
在这里插入图片描述

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

class Solution {
    
    
    public ListNode reverseList(ListNode head) {
    
    
        //1.设置两个指针。一个指向null,一个指向头节点
        ListNode firstnode = null;
        ListNode nextnode = head;
        //2.将两个指针一起向后移动。直到nextnode指向尾节点的下一个节点,此时firstnode指向尾节点
        while(nextnode != null){
    
    
            //把nextnode的下一个节点先存下来
            ListNode temp = nextnode.next;
            //修改nextnode的next
            nextnode.next = firstnode;
            //将两个指针一起向后移一个节点
            firstnode = nextnode;
            nextnode = temp;
        }
        //3.返回firstnode
        return firstnode;
    }
}

复杂度分析

时间复杂度:O(n)
空间复杂度:O(1)

猜你喜欢

转载自blog.csdn.net/taroriceball/article/details/111475396