[英]reverse order of linked list by push
我試圖做一個函數,以更改節點的指針的順序,以便原始列表是相反的。
我的解決方案基於迭代主列表,然后反轉每個2個相鄰節點的順序: (n1)->(n2)
(n1)<-(n2)
在第一次迭代后將是(n1)<-(n2)
。
我的嘗試:
Node push1(Node* curr) {
if(curr == NULL || *curr == NULL) {
return NULL;
}
Node temp = (*curr)->next;
if(temp == NULL) {
return NULL;
}
(*curr)->next = *curr;
return temp;
}
/*******************************/
void reverse2(Node* head) {
Node curr = *head;
while(curr != NULL) {
curr = push1(&curr);
}
}
問題:我遇到了無限循環。 我試圖解決此問題,但是列表沒有顛倒順序。 有沒有辦法使用這種方法push1()
可行?
注意:我不尋求與3指針或遞歸的解決方案。
這有效,但有點傻
Node* push1(Node** prev, Node* curr)
{
Node* ret = curr->next;
curr->next = *prev;
(*prev)=curr;
return ret;
}
void reverse2(Node** head)
{
Node* prev = *head;
if(!prev) return;
Node* curr = prev->next;
if(!curr) return;
prev->next = 0;
while(curr)
{
curr = push1(&prev,curr);
}
*head = prev;
}
結合使用std :: stack <>數據結構和std :: vector <>,這相當容易。 回想一下,堆棧是一種容器,旨在在LIFO上下文(后進先出)中操作,在該上下文中,僅從容器的一端插入和提取元素。
因此,在您所處的情況下,您將創建一個堆棧,按照已擁有的順序將節點添加到堆棧中,然后將其從堆棧中彈出,以顛倒節點的順序。
我已經草繪了執行此操作的代碼,但是請注意,該代碼未經測試,因此您應該能夠將此想法適應您的情況:
#include <stack>
#include <vector>
std::vector<Node> reverseNodes(Node* currNode, Node* startNode) {
std::vector<Node> reversed;
std::stack<Node> nodeStack;
// First add nodes to the stack:
for (Node* aNode = currNode; aNode != startNode; aNode = aNode->next) {
nodeStack.push(aNode);
}
// Next add your starting node to the stack (last-in):
nodeStack.push(startNode);
// Popping off of the stack reverses the order:
while (!nodeStack.empty()) {
reversed.push_back(nodeStack.pop());
}
// Return the nodes ordered from last->first:
return reversed;
}
這是不可讀或可移植的,但不使用遞歸或其他變量:
struct list {
list *next;
/* ... */
};
list *
reverse(list *l)
{
list *head = nullptr;
while (l) {
head = (list *) ((uint64_t) head ^ (uint64_t) l->next);
l->next = (list *) ((uint64_t) l->next ^ (uint64_t) head);
head = (list *) ((uint64_t) head ^ (uint64_t) l->next);
l = (list *) ((uint64_t) l ^ (uint64_t) head);
head = (list *) ((uint64_t) head ^ (uint64_t) l);
l = (list *) ((uint64_t) l ^ (uint64_t) head);
}
return head;
}
訣竅是使用xor
交換 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.