链表交换相邻节点

leetcode 24. Swap Nodes in Pairs

方法一:用指针的指针的方法(leetcode大神思路很巧妙)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
         ListNode **pp = &head;
		 ListNode*a, *b;
		 while ((a=*pp)&&(b=a->next))
		 {
			 a->next = b->next;
			 b->next = a;
			 *pp = b;
			 pp = &(a->next);
		 }
		 return head;
    }
};

方法二:用递归的方法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(!head || !head->next) return head;
        ListNode* NewNode = head->next;
        head->next = swapPairs(NewNode->next);
        NewNode->next = head;
        return NewNode;
    }
};

你可能感兴趣的:(刷题总结,链表)