【LeetCode】Swap Nodes in Pairs

来源:互联网 发布:薛之谦淘宝店铺链接 编辑:程序博客网 时间:2024/05/22 14:46

题目描述:

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.

题目要求不能只换val,需要将整个节点交换。用两个变量储存下就好了。

代码:

class Solution {public:ListNode *swapPairs(ListNode *head) {ListNode *res = new ListNode(0);ListNode *node = res;while (head){ListNode *l1(NULL);ListNode *l2(NULL);if (head){l1 = head;head = head->next;}if (head){l2 = head;head = head->next;}if (l2){node->next = l2;node = node->next;}if (l1){node->next = l1;node = node->next;}}node->next=NULL;return res->next;}};


0 0
原创粉丝点击