Leecode之反转链表

简介: Leecode之反转链表

一.题目及剖析

https://leetcode.cn/problems/reverse-linked-list/description/

二.思路引入

设定三个指针,n1指向空, n2指向head,n3指向下一个元素,将n2->next指向n1,然后三个指针向后遍历重复直到n2为空,这里需要注意的是n2为空之前,n3可能已经为空,所以,我们在移动n3指针的时候要判断一下此时的n3指针是否为空,如果为空,n3精不在进行移动

三.代码引入

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode *n1, *n2, *n3;
    n1 = NULL;
    n2 = n3 = head;
    if(head)
    n3 = head->next;
    while(n2)
    {
        n2->next = n1;
        n1 = n2;
        n2 = n3;
        if(n3)
        n3 = n3->next;
    }
    return n1;
}
相关文章
Leecode之合并两个有序链表
Leecode之合并两个有序链表
|
索引
【LeeCode】每日一题:复制带随机指针的链表
【LeeCode】每日一题:复制带随机指针的链表
193 0
|
Python
LeeCode-合并两个有序链表(python)递归
LeeCode-合并两个有序链表(python)递归
235 0
LeeCode-合并两个有序链表(python)递归
|
Java C++
Leecode 876. 链表的中间结点
Leecode 876. 链表的中间结点
122 0
Leecode 24. 两两交换链表中的节点
Leecode 24. 两两交换链表中的节点
117 0