【LeetCode】24. Swap Nodes in Pairs C语言

来源:互联网 发布:github ssh项目源码 编辑:程序博客网 时间:2024/06/03 17:53

LeetCode解题心得,欢迎交流! 第二日

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; *///方法1struct ListNode* swapPairs(struct ListNode* head) {    struct ListNode *dummy=(struct ListNode*)malloc(sizeof(struct ListNode));    dummy->next = head;    struct ListNode *cur=dummy;        while(cur->next!=NULL && cur->next->next!=NULL)    {        struct ListNode *first=cur->next;        struct ListNode *second=cur->next->next;        first->next = second->next;        cur->next=second;        second->next=first;        cur=cur->next->next;    }    return dummy->next;}     //方法2 递归struct ListNode* swapPairs(struct ListNode* head) {    if(head == NULL || head->next ==NULL) return head;    struct ListNode *p=head->next;        head->next=swapPairs(head->next->next);    p->next=head;    return p;}


0 0
原创粉丝点击