给出 1->2->3->4, 你应该返回的链表是 2->1->4->3。
思路:
(注意当节点数有单数时不用交换)建立一个新链表还有两个指针,进行交换。代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: /** * @param head a ListNode * @return a ListNode */ ListNode* swapPairs(ListNode* head) { if(head==NULL||head->next==NULL) return head; ListNode *p = new ListNode(0); p->next = head; ListNode *r = p; while(p->next != NULL &&p->next->next != NULL){ ListNode *a =p->next; ListNode *b = p->next->next; a->next=b->next; b->next =a; p->next =b; p= p->next->next; } return r->next; // Write your code here } };
个人感悟:
不要忘记特殊情况。
