
用栈进行替换:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr)
return head;
ListNode* ptr = head;
stack<ListNode*> data;
ListNode* addhead = new ListNode(0);
ListNode* p = addhead;
int num = 0;
while (ptr != nullptr) {
if (num<2) {
data.push(ptr);
ptr = ptr->next;
num++;
}
else {
for (int i = 0; i<2; i++) {
ListNode* temp = data.top();
p->next = temp;
p = temp;
data.pop();
}
num = 0;
}
}
while (!data.empty()) {
ListNode* temp = data.top();
p->next = temp;
p = temp;
data.pop();
}
p->next = nullptr;
return addhead->next;
}
};
本文介绍了一种使用栈数据结构来实现链表中元素成对交换的算法。通过将每对节点压入栈中,再依次弹出以达到交换的目的,最后返回修改后的链表头指针。
1653

被折叠的 条评论
为什么被折叠?



