leetcode24(两两交换链表中的节点)--C语言实现

求:spa

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。code

你不能只是单纯的改变节点内部的值,而是须要实际的进行节点交换。递归

 

示例:it

给定 , 你应该返回 1->2->3->42->1->4->3

 

解:io

递归解法:
/**
 * 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* next = head->next;
    head->next = swapPairs(next->next);
    next->next = head;
     return  next;    
}
 
循环解法:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
 
struct  ListNode* swapPairs( struct  ListNode* head){
     struct  ListNode* pre = ( struct  ListNode*)malloc( sizeof ( struct  ListNode));
    pre->next = head;
     struct  ListNode* tmp = pre;
     while (tmp->next!=NULL && tmp->next->next!=NULL){
         struct  ListNode* first = tmp->next;
         struct  ListNode* second = first->next;
        tmp->next = second;
        first->next = second->next;
        second->next = first;
        tmp = first;
    }
     return  pre->next;
}
相关文章
相关标签/搜索