刷算法题之链表专题

leetcode24

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) {
    struct ListNode *dummy_head = (struct ListNode *)malloc(sizeof(struct ListNode)); // 虚拟头节点
    struct ListNode *cur; //当前节点
    dummy_head->next = head;   
    cur = dummy_head;
    while(cur->next !=NULL && cur->next->next != NULL)
    {
        struct ListNode *temp;  // 记录临时节点
        struct ListNode *temp1;

        temp = cur->next;
        temp1 = cur->next->next->next;

        cur->next = cur->next->next;
        cur->next->next = temp;
        temp->next = temp1;
        cur = cur->next->next;
    }
    return dummy_head->next;
}

leetcode19

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    struct ListNode *dummy_head = (struct ListNode *)malloc(sizeof(struct ListNode));
    dummy_head->next =head;
    struct ListNode *fast = dummy_head;
    struct ListNode *slow = dummy_head;;
    //n++;
    while(n-- && fast != NULL)
    {
        fast = fast->next;
    }
    fast = fast->next;
    while(fast != NULL)
    {
        fast = fast->next;
        slow = slow->next;        
    }
    slow->next = slow->next->next;
    return dummy_head->next;
}

leetcode142
环形链表,使用快慢指针

struct ListNode *detectCycle(struct ListNode *head) {
    struct ListNode *fast = head;
    struct ListNode *slow= head;
    while(fast != NULL && fast->next != NULL)
    {
        fast = fast->next->next;
        slow = slow->next;
        if(fast == slow)
        {
            struct ListNode *temp1 = fast;
            struct ListNode *temp2 = head;
            while(temp1 != temp2)
            {
                temp1 = temp1->next;
                temp2 = temp2->next;
            }
            return temp1;
        }
    }
    return NULL; // 没有找到
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可厉害的土豆

你的鼓励是我创作的源泉

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值