您的位置:首页 > Web前端 > Node.js

leetcode: Swap Nodes in Pairs

2013-10-28 22:34 435 查看
http://oj.leetcode.com/problems/swap-nodes-in-pairs/

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.


思路

每次读两个节点插入新链表,因为是指针操作,不占用额外空间。最后需要把tail指针的next设为NULL。例如链表为p1->p2->p3->p4的情况,如果最后不修改p3->next,那么就会出现一个环:p2->p1->p4->p3->p4->...

class Solution {
public:
void insertTwoNodes(ListNode *p1, ListNode *p2, ListNode *&head, ListNode *&tail) {
if (NULL == head) {
head = tail = p2;
}
else {
if (p2 != NULL) {
tail->next = p2;
tail = p2;
}
}

if (NULL == head) {
head = tail = p1;
}
else {
tail->next = p1;
tail = p1;
}
}

ListNode *swapPairs(ListNode *head) {
ListNode *swapped_head = NULL, *swapped_tail = NULL;

while (head != NULL) {
ListNode *p1 = NULL, *p2 = NULL;

p1 = head;
head = head->next;

if (head != NULL) {
p2 = head;
head = head->next;
}

insertTwoNodes(p1, p2, swapped_head, swapped_tail);
}

if (NULL != swapped_tail) {
swapped_tail->next = NULL;
}

return swapped_head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: