一、 问题描述
Leecode第二十四题,题目为:
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
问题理解为:
给定一个链表,每两个相邻节点交换一次,并返回它的头部。
您不能修改列表节点中的值,只能修改节点本身。
例子:
给定1->2->3->4,您应该返回列表为2->1->4->3。
二、算法思路
1、
2、
三、实现代码
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *dummy = new ListNode(-1), *pre = dummy;
dummy->next = head;
while (pre->next && pre->next->next) {
ListNode *t = pre->next->next;
pre->next->next = t->next;
t->next = pre->next;
pre->next = t;
pre = t->next;
}
return dummy->next;
}
};