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;
}
相关文章
|
2月前
Leecode之合并两个有序链表
Leecode之合并两个有序链表
|
2月前
Leecode之分割链表
Leecode之分割链表
|
2月前
Leecode之环形链表进阶
Leecode之环形链表进阶
|
2月前
Leecode之相交链表
Leecode之相交链表
|
2月前
Leecode之环形链表
Leecode之环形链表
|
2月前
Leecode之随机链表的复制
Leecode之随机链表的复制
|
10月前
|
索引
【LeeCode】每日一题:复制带随机指针的链表
【LeeCode】每日一题:复制带随机指针的链表
46 0
|
Java C++
Leecode 876. 链表的中间结点
Leecode 876. 链表的中间结点
37 0
Leecode 24. 两两交换链表中的节点
Leecode 24. 两两交换链表中的节点
46 0
|
算法
Leecode 25. K 个一组翻转链表
Leecode 25. K 个一组翻转链表
46 0