[LeedCode OJ]#24 Swap Nodes in Pairs

【 声明:版权所有,转载请标明出处,请勿用于商业用途。 联系信箱: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;}};

版权声明:本文为博主原创文章,如果转载,请注明出处

经受雨,面对另一个轮回。

[LeedCode OJ]#24 Swap Nodes in Pairs

相关文章:

你感兴趣的文章:

标签云: