題目描述
給你一個鏈表,兩兩交換其中相鄰的節點,并返回交換后鏈表的頭節點。你必須在不修改節點內部的值的情況下完成本題(即,只能進行節點交換)。
class Solution {
public:ListNode* swapPairs(ListNode* head) {if(head==NULL||head->next==NULL){return head;}ListNode* pre = new ListNode(-1);pre->next = head;ListNode* temp = pre;ListNode* l1 = head;ListNode* l2 = head->next;while (l2){l1->next=l2->next;pre->next=l2;l2->next=l1;l1=l1->next;if(l1==NULL)break;l2=l1->next;pre=pre->next->next;}return temp->next;}
};
小結:后來才看到不能修改結點值,但是也不難