Leetcode24.两两交换链表中的节点(C语言)

Leetcode24.两两交换链表中的节点(C语言)

数据结构-链表:算法与数据结构参考

题目:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。例:
输入:1->2->3->4
输出:2->1->4->3.

思路:
递归
在这里插入图片描述
代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* swapPairs(struct ListNode* head){
    if(head==NULL || head->next==NULL) return head;
    
    struct ListNode *nex=head->next;
    
    head->next = swapPairs(nex->next);//递归完head->next->next之后所有节点交换完毕
    nex->next = head;
    
    return nex;
}
发布了42 篇原创文章 · 获赞 0 · 访问量 612

猜你喜欢

转载自blog.csdn.net/jeanlu/article/details/104247474
今日推荐