简体   繁体   English

循环单链列表中任何选定索引的返回指针

[英]Return Pointer of any selected index in circular singly linked list

I designed this code so that I can get a pointer of any position that user wants in a circular singly linked list, I am using cout to return pointer, I want such a mechanism that I can use it with my other function instead of re writing the whole code again, for that I need to do something with return type which is void right now 我设计了这段代码,以便可以在圆形单链接列表中获取用户想要的任何位置的指针,我正在使用cout返回指针,我想要一种可以与其他函数一起使用而不用重写的机制再次整个代码,为此,我需要使用返回类型做一些事情,现在它是无效的

Here is the function .. 这是功能..

void pointer_to_node(int index){
    Node*temptr;
    temptr = new Node;
    temptr = firstptr;

    Node*temptr2;
    temptr2 = new Node;
    temptr2 = NULL;
    int count = 1;

    while (temptr!=temptr2){
        if(count==index){
            cout << "Required Pointer is : ";
            cout<< temptr;}

        count++;
        temptr2=firstptr;
        temptr=temptr->nextptr;
    }

    if (index>size_of_list())
    {
        temptr=NULL;
        cout<< "Can't You think in bounds. Take your NULL Pointer ";
        cout << temptr;
        delete temptr;
        delete temptr2;
    }
}

You just need to return a Node * . 您只需要返回一个Node *

However, while you're doing that, you also really need to take out these: temptr = new Node; 但是,在执行此操作时,您实际上还需要删除这些内容: temptr = new Node; lines, as well as the delete s, as you're leaking memory there. 行,以及delete ,因为您正在那里泄漏内存。 You just immediately discard those new nodes by reassigning the pointers. 您只需通过重新分配指针立即丢弃这些新节点。 The delete s at the end will delete the wrong nodes entirely, and aren't called in all cases anyway. 最后的delete会完全删除错误的节点,并且无论如何都不会被调用。

And if you pass an index of 0, your loop might take a very long time indeed. 而且,如果传递的索引为0,则循环可能确实需要很长时间。

I assume you have good reason for wanting to return NULL if you loop around the list. 我假设您有充分的理由要在列表中循环时返回NULL。

Something like the following should suffice: 如下所示就足够了:

Node *pointer_to_node(int index)
{
    Node *temp = firstptr;
    while(index-- != 0) {
        temp = temp->nextPtr;
        if(temp == firstptr) return NULL;
    }
    return temp;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM