24. 两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
Example:
给定 1->2->3->4,你应该返回 2->1->4->3。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| struct ListNode* swapPairs(struct ListNode* head) { struct ListNode* first = (struct ListNode*)malloc(sizeof(struct ListNode)); first->next = head; struct ListNode* first1 = first; while(first->next && first->next->next){ struct ListNode* one = first->next; struct ListNode* two = first->next->next; one->next = two->next; first->next = two; two->next = one; first = one; } return first1->next; }
|
思路:
用一个指针从开始读,如果可以读到该节点与下个节点,就将这两个结点交换位置,这时需要注意与前后的结点连接。
为了方便,用一个头结点来完成这个连接的工作。