【 声明:版权所有,转载请标明出处,请勿用于商业用途。 联系信箱:libin493073668@sina.com】
题目链接:https://leetcode.com/problems/swap-nodes-in-pairs/
题意:
给你一个链表,要你对每两个相邻的节点进行交换
思路:
链表的结点不用想都知道通过next的指向来找,交换也是如此,通过改变指向就行了,但是注意要将尾结点的next指向空,否则要超时
/**
* 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) {
if(head==nullptr || head->next==nullptr)
return head;
ListNode *newlist = new ListNode(0);
ListNode *ptr = newlist;
ListNode *cur = head;
while(cur && cur->next)
{
ListNode *pnext = cur->next->next;
ptr->next = cur->next;
ptr = ptr->next;
ptr->next = cur;
ptr = ptr->next;
ptr->next = nullptr;
cur = pnext;
}
if(cur) ptr->next = cur;
return newlist->next;
}
};