題意:
給你一個鏈表,要你對每兩個相鄰的節點進行交換
思路:
鏈表的結點不用想都知道通過next的指向來找,交換也是如此,通過改變指向就行了,但是注意要將尾結點的next指向空,否則要超時
/** * 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==nullptr || head->next==nullptr) return head; ListNode *newlist = new ListNode(0); ListNode *ptr = newlist; ListNode *cur = head; while(cur && cur->next) { ListNode *pnext = cur->next->next; ptr->next = cur->next; ptr = ptr->next; ptr->next = cur; ptr = ptr->next; ptr->next = nullptr; cur = pnext; } if(cur) ptr->next = cur; return newlist->next; } };