leetcode24.两两交换链表中的节点

1.题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
2.示例:
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
3.思路
循环遍历链表,当只有一个节点时特殊处理。
4.代码
ListNode* swapPairs(ListNode* head) {
ListNode* tail=new ListNode(INT_MIN);
ListNode* newtail=tail;
ListNode* ptr=head;
while(ptr!=NULL&&ptr->next!=NULL){
ListNode* tmp=ptr->next->next;
newtail->next=ptr->next;
newtail=newtail->next;
newtail->next=ptr;
newtail=newtail->next;
newtail->next=NULL;//newtail有next节点
ptr=tmp;
}
if(ptr!=NULL) newtail->next=ptr; //处理到最后只剩一个节点
return tail->next;
}

猜你喜欢

转载自blog.csdn.net/qq_14962179/article/details/85758415