链表OJ之 反转单链表

点我做题

请看题目:

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例1:

输入:head = [1, 2, 3, 4, 5]

输出:[5, 4, 3, 2, 1]

示例2:

输入:head = [1, 2]

输出:[2, 1]

示例3:

输入:head = [ ]

输出:[ ] 


解题:

思路一:取结点头插

大体思路就是用 cur 遍历一遍链表,cur 前后各有 next 和 newhead ,通过改变 cur 的下一个结点实现链表的反转。

我是图示

代码实现:

struct ListNode* reverseList(struct ListNode* head){
    struct ListNode*cur = head;
    struct ListNode*newhead = NULL;
   
    while(cur)
    {
        //更新头
        struct ListNode*next = cur->next;
        cur->next = newhead;
        //前进
        newhead = cur;
        cur = next;
    }
    return newhead;
}

思路二:三指针反转法

与思路一类似,创建三个指针 n1, n2 ,n3 ,通过改变 n2 的下一个结点改变链表的方向。

我是图示 

代码实现:

struct ListNode* reverseList(struct ListNode* head){
    
    //排除三个结点以下的情况
    if(head == NULL||head->next == NULL)
    {
        return head;
    }
    //确定位置
    struct ListNode* n1,*n2,*n3;
    n1 = head;
    n2 = n1->next;
    n3 = n2->next;
    n1->next = NULL;
    //中间结点不为空,继续修改指向
    while(n2)
    {
        n2->next = n1;
        n1 = n2;
        n2 = n3;
        if(n3)
            n3 = n3->next;
    }
    return n1;
}

总结:

这篇博客为反转链表提供了两种解决方案,都属于迭代类型,你学会了吗? 

猜你喜欢

转载自blog.csdn.net/Claffic/article/details/129331743