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

24、Swap Nodes in Pairs

2015-01-23 15:52 211 查看
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.

Linked List

ListNode *swapPairs(ListNode *head) {
//交换临近节点,不需要额外空间,不能修改节点中的值
ListNode *headL = NULL, *first = NULL, *second = NULL, *next = NULL, *pre = NULL;
//确定头结点
if (head)
headL = first = head;
if (head && head -> next)
headL = second = head -> next;
while (first && second)
{
next = second -> next;
if (pre)
pre -> next = second;
second -> next = first;
first -> next = next;
pre = first;
first = next;
if (first)
second = first -> next;
}
return headL;

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