LeetCode解題心得,歡迎交流! 第二日
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//方法1
struct 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;
}