Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
交换邻近的两个节点,但是不能用额外的链表空间,也不能修改节点的值来实现交换效果。
思路:加一个头结点,问题会好处理一些,剩下的就是指针的问题了。
/** * 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 == NULL) return head; if(head->next==NULL) return head; ListNode* left = head; ListNode* right=head->next; ListNode tem(0); ListNode* h = &tem; h->next = head; head = h; while(h->next!=NULL&&h->next->next!=NULL){ left->next = right->next; right->next = left; h->next = right; h = left; if(h->next!=NULL&&h->next->next!=NULL){ left = left->next; right = left->next; } } head = head->next; return head; } };