解决此题方法,每次选取两个node改变它们的位置,注意若最后只剩下一个元素则不需要改变位置
代码
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
if(head==NULL||head->next==NULL)
return head;
ListNode *first, *second, *newHead, *p, *tempTail;
newHead = new ListNode(0);
tempTail = newHead;
p = head;
while(p!=NULL&&p->next!=NULL)
{
first = p;
second = p->next;
p = second->next;
first->next = tempTail->next;
tempTail->next = second;
second->next = first;
tempTail = first;
}
//将剩余的单个节点加上
if(p!=NULL)
tempTail->next = p;
return newHead->next;
}
};
311

被折叠的 条评论
为什么被折叠?



