Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can 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) { ListNode *p; p=head; int temp; if(!p) return p; if(!p->next) return p; while(p && p->next) { temp=p->val; p->val=p->next->val; p->next->val=temp; p=p->next->next; } return head; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。