singly linked chain printing c++

与世无争的帅哥 提交于 2019-12-02 11:46:21

Suppose your list is cyclical, you can use this:

struct Node *n = begin;

if (n != NULL) {
    //do something on it
    ...
    for (n = begin->Succ; n != begin; n = n->Succ) {
    }
}

or

struct Node *n = begin;
if (n != NULL) {        
    do {        
        //do something
        ...
        n = n->Succ;
    } while (n != begin)
}

Here are two recommendations: 1) Sort the list first, then print all nodes; 2) Create another list (indices) to the data and sort those links (don't need data in those nodes).

Sorting List First

An often used technique is to order the nodes in the order you want them printed. This should involve changing the link fields.
Next, start at the head node and print each node in the list (or the data of each node in the list).

Using an Index list

Create another linked list without the data fields. The links in this list point to the data fields in the original list. Order the new list in the order you want the nodes printed.
This technique preserves the order of creation of the first list and allows different ordering schemes.

Changing Links

Since you're writing your own Linked List, the changing of the links is left as an exercise as I'm not getting paid to write your code. There are many examples on SO as well as the web for sorting and traversing linked lists.

You just want to do something like this:

void Set::display(ostream &out) const {
    for(int i=0; i<Num; i++) {
        out << Pool[i] << " ";
    }
    out << endl;
}

An ostream behaves as cout would.

Acorbe

It's hard to get your question. If you want to print the array to screen you should consider writing a display() like:

#include <iostream>
#include <iterator>
void Set::display() const {
   ostream_iterator<int> out_it (cout," ");
   copy(Pool,Pool+Num,out_it);   
   cout << endl;
}

or if you want to write to a ostream& (as it is pointed out in the answer by @alestanis)

#include <iostream>
#include <iterator>
void Set::display(ostream &out) const {
   ostream_iterator<int> out_it (out," ");
   copy(Pool,Pool+Num,out_it);   
   out << endl;
}

Without testing, I'd do something like this. (Assumes the last node has Succ set to NULL, as I would recommend it does.)

void LoopList(struct Node *head)
{
    for (struct Node *p = head; p != null; p = p->Succ)
    {
        // Do whatever with this node
        Print(p);
    }
}

I think I was over thinking it. Anyway here is what I ended up doing. Now I just need to add some formatting for the commas and im all set.

Node * Temp;
Temp = new (nothrow) Node;
Temp = Head;
out << "{";
while(Temp->Succ)
{
      out << Temp->Item;
      Temp = Temp->Succ;
}
out << '}' << endl;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!