力扣 206. 反转链表 C语言实现

题目描述:

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

题目链接

 题目解析:

循环

struct ListNode* reverseList(struct ListNode* head){

    struct ListNode* newHead=NULL;
    struct ListNode* pre = head;
    while(pre)
    {
        struct ListNode* next = pre->next;
        pre->next = newHead;
        newHead = pre;
        pre = next;
    }
    return newHead;

}

更加清晰的思路:定义前一个节点、当前节点和后一个节点,循环链表。每次将当前节点指向当前节点的前一个节点,并依次向后移动这三个节点。代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL)
        {
            return head;
        }
        ListNode* pre = NULL;
        ListNode* cur = head;
        ListNode* nex = head->next;
        while(nex)
        {
            cur->next=pre;
            pre = cur;
            cur = nex;
            nex = nex->next;
        }
        cur->next = pre;
        return cur;
    }
};

注意:while循环结束后需要将当前节点的下一个指向前一个节点,否则会断节。 

递归

struct ListNode* reverseList(struct ListNode* head){
    if(head==NULL)
    {
        return NULL;
    } 
    if(head->next==NULL)
    {
        return head;
    }
    struct ListNode* cur = head;
    head = reverseList(head->next);
    struct ListNode* now = head;
    while(now->next!=NULL)
    {
        now = now->next;
    }
    now->next = cur;
    cur->next = NULL;
    
    
    return head;

 

}
struct ListNode* reverseList(struct ListNode* head){
    if(head==NULL)
    {
        return NULL;
    } 
    if(head->next==NULL)
    {
        return head;
    }
    struct ListNode* newHead = reverseList(head->next);
    head->next->next = head;
    head->next=NULL;
    
    return newHead;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值