【Leetcode】Swap Nodes in Pairs

来源:互联网 发布:java里调用window.open 编辑:程序博客网 时间:2024/05/04 23:27

问题

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.


代码

class Solution {public:    ListNode *swapPairs(ListNode *head) {        if (!head) {return NULL;}if (head->next == NULL) {return head;}ListNode *returnNode = NULL;ListNode *lastNode = NULL;while (head) {if (head->next) {if (!returnNode) {returnNode = head->next;head->next = returnNode->next;returnNode->next = head;lastNode = head;}else{lastNode->next = head->next;head->next = head->next->next;lastNode->next->next = head;lastNode = head;}}else{break;}head=head->next;}return returnNode;    }};


分析

链表,没有什么难度,一次性通过~~

总结

n/a

0 0
原创粉丝点击