Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用指针反转列表中的元素_C++_Arrays_Algorithm_List_Pointers - Fatal编程技术网

C++ 使用指针反转列表中的元素

C++ 使用指针反转列表中的元素,c++,arrays,algorithm,list,pointers,C++,Arrays,Algorithm,List,Pointers,可能重复: 如果不使用数组 (我只能使用指针,这是我的问题) 将列表视为一个堆栈,弹出元素并将其推入新列表。考虑一个名为lst的列表,它允许我们向前向后移动,即它是双链接列表 只需交换开始节点和结束节点的内容,即可反转列表lst void reverse(lst *beg,lst *end) { lst temp; while(beg!=end) { //swap the content of the nodes *temp=*beg;

可能重复:

如果不使用
数组


(我只能使用指针,这是我的问题)

将列表视为一个堆栈,弹出元素并将其推入新列表。

考虑一个名为
lst
的列表,它允许我们向前向后移动,即它是
双链接列表

只需交换开始节点和结束节点的内容,即可反转列表
lst

void reverse(lst *beg,lst *end)
{
    lst temp;
    while(beg!=end)
    {
        //swap the content of the nodes
        *temp=*beg;
        *beg=*end;
        *end=*temp;

        beg=beg->Next();//move to next node
        end=end->prev();//move to previous node
    }
}


如果它是一个
单链表
,您可以使用
堆栈

void reverse(lst* beg)
{
    stack<lst*> stc;
    lst* temp=beg;
    lst* temp1=beg;
    while(temp)//store pointers to lst nodes in stack
    {
        stc.push(temp);
        temp=temp.Next();
    }
    while(temp1)//pop the stack by inserting it into list from beginning
    {
       *temp1=*stc.top();
        temp1=temp1.Next(); 
        stc.pop();
    }
}
void reverse(lst*beg)
{
堆栈stc;
lst*temp=beg;
lst*temp1=beg;
while(temp)//在堆栈中存储指向lst节点的指针
{
标准推力(温度);
temp=temp.Next();
}
while(temp1)//通过从开始将堆栈插入列表来弹出堆栈
{
*temp1=*stc.top();
temp1=temp1.Next();
stc.pop();
}
}

您不需要交换节点内容或堆栈。如果要反转单个链表,只需在迭代循环中使用一对指针加上中间指针即可。完成后不要忘记更新头部指针

void reverse_list(node **head)
{
    node *cur=NULL, *nxt=NULL;

    if (!(head || *head || (*head)->next))
        return;

    nxt = *head;
    while (nxt != NULL)
    {
        node *prv = cur;
        cur = nxt;
        nxt = nxt->next;
        cur->next = prv;
    }

    *head = cur;
}
假设列表节点如下所示:

typedef struct node
{
    ..data..
    struct node *next;
} node;
并对其进行适当管理,然后您可以这样调用:

node *head = NULL;

...fill the list...

reverse_list(&head);

“我只能使用指针,这是我的问题”-原始指针?然后你在写C。关于你的问题,如果它是一个单链表,那么你不能通过遍历它一次来避免O(n)复杂性。如果它是一个双链表,那么你可以在相反的方向上遍历它。也许有帮助……MiaioDoice,所以STL/Boost不是C++?“算了吧!”詹姆斯,他没有给我们看任何代码,所以我做了一个假设。就STL而言,它的容器是类型安全和异常安全的。无论如何,这是离题的。@MihaiTodor我的意思是,我必须使用指针来反转列表。我已经想到了一个反转列表的解决方案,但我必须使用数组,我不允许这样做。因此,我要求提供一个如何做的示例,以便我可以继续这个练习。谢谢大家的帮助,我会研究你给我的答案,看看我能从中得到什么。我想他更愿意做“就地”手术,以保存记忆。为此,他将需要两个指向当前节点和前一个节点的辅助指针,并在遍历列表时更新节点之间的链接一次。“只需使用c++的列表容器类”——他可能不希望这样做,因为它是作为双链接列表实现的,对于性能要求严格的代码来说,这并不总是最佳选择。