24两两交换链表中的节点
题目链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
本身只是实现并不难,直接换一下val就行了。但这道题不准偷懒,必须交换节点,所以是一道重视基本功的题目,理不清了就画个图好了。需要注意一下原链表只有0个或1个节点的情况。
/**
* 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* result=head;
ListNode* tem=NULL;
ListNode* point=NULL;
if(head!=NULL&&head->next!=NULL){
result=head->next;
tem=result->next;
result->next=head;
head->next=tem;
point=result->next;
while(point->next!=NULL&&point->next->next!=NULL){
tem=point->next->next;
// cout<<tem->val<<endl;
point->next->next=point->next->next->next;
tem->next=point->next;
point->next=tem;
point=point->next->next;
}
}
return result;
}
};