0

Hi everyone trying to translate an older C program that uses array of structures into C++ program that uses linked lists. I'm a total C++ newb and I'm a little confused on the syntax of setting up a linked list in C++.... here's my code:

#include <iostream> 
#include <stdlib.h>
#include <string>
#include <ctype.h>
#include <fstream>

using namespace std;


struct Video { 
char video_name[1024];      
int ranking;                // Number of viewer hits
char url[1024];             // Video URL
struct Video *next;  // pointer to Video structure
} 


struct Video* Collection = new struct Video;
Collection *head = NULL;                    // EMPTY linked list

In my old program Collection was an array of Video. How can I make Collection be a linkedlist of Video nodes? I am currently getting errors saying on the last two lines code saying: expected initializer before 'Collection' and expected constructor, destructor or type conversion before '*' conversion. I know my syntax is definately wrong, but I guess I dont understand how to create a linked list of Videos inside of Collection...

accraze
  • 1,522
  • 7
  • 20
  • 46
  • 2
    If you don't know how to implement a linked list, use the STL's List class – Sidharth Mudgal Oct 07 '12 at 00:05
  • 2
    **Get a book !! Get a book !!** Here is some help. http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – DumbCoder Oct 07 '12 at 00:08
  • 2
    @SidharthMudgal Indeed, even if you *do* know how to implement a linked list, STL's will be solid, tested, and optimized, and with lots of useful helper functions like std::sort already there. Except as a learning exercise, there is *zero* reason to be writing your own linked list. – Andrew Lazarus Oct 07 '12 at 00:11

2 Answers2

2

The c++ answer is:

struct Video { 
    std::string video_name;     
    int ranking;                // Number of viewer hits
    std::string url;             // Video URL
} 

std::list<Video> list_of_videos
andre
  • 7,018
  • 4
  • 43
  • 75
0

You've defined Collection as a variable of type pointer-to-Video. On the next line you treat it as a type, which makes no sense. All you need is this:

Video *head = NULL;

head represents the linked list. You don't need another variable.

OTOH, if you really want to use C++ properly, I'd suggested sticking with the array solution unless your usage patterns somehow warrant linked-list semantics. If it's an array of known size, you have two choices:

Video videos[N];
std::array<Video, N> videos; // Preferred in C++11

Otherwise, use a std::vector<T>:

std::vector<Video> videos;

If it really must be a linked list, consider using std::list<T>:

std::list<Video> videos;

In all such cases, you should leave out struct Video *next;.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365