Search Results

Search found 33873 results on 1355 pages for 'linked list'.

Page 5/1355 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Linked List manipulation, issues retrieving data c++

    - by floatfil
    I'm trying to implement some functions to manipulate a linked list. The implementation is a template typename T and the class is 'List' which includes a 'head' pointer and also a struct: struct Node { // the node in a linked list T* data; // pointer to actual data, operations in T Node* next; // pointer to a Node }; Since it is a template, and 'T' can be any data, how do I go about checking the data of a list to see if it matches the data input into the function? The function is called 'retrieve' and takes two parameters, the data and a pointer: bool retrieve(T target, T*& ptr); // This is the prototype we need to use for the project "bool retrieve : similar to remove, but not removed from list. If there are duplicates in the list, the first one encountered is retrieved. Second parameter is unreliable if return value is false. E.g., " Employee target("duck", "donald"); success = company1.retrieve(target, oneEmployee); if (success) { cout << "Found in list: " << *oneEmployee << endl; } And the function is called like this: company4.retrieve(emp3, oneEmployee) So that when you cout *oneEmployee, you'll get the data of that pointer (in this case the data is of type Employee). (Also, this is assuming all data types have the apropriate overloaded operators) I hope this makes sense so far, but my issue is in comparing the data in the parameter and the data while going through the list. (The data types that we use all include overloads for equality operators, so oneData == twoData is valid) This is what I have so far: template <typename T> bool List<T>::retrieve(T target , T*& ptr) { List<T>::Node* dummyPtr = head; // point dummy pointer to what the list's head points to for(;;) { if (*dummyPtr->data == target) { // EDIT: it now compiles, but it breaks here and I get an Access Violation error. ptr = dummyPtr->data; // set the parameter pointer to the dummy pointer return true; // return true } else { dummyPtr = dummyPtr->next; // else, move to the next data node } } return false; } Here is the implementation for the Employee class: //-------------------------- constructor ----------------------------------- Employee::Employee(string last, string first, int id, int sal) { idNumber = (id >= 0 && id <= MAXID? id : -1); salary = (sal >= 0 ? sal : -1); lastName = last; firstName = first; } //-------------------------- destructor ------------------------------------ // Needed so that memory for strings is properly deallocated Employee::~Employee() { } //---------------------- copy constructor ----------------------------------- Employee::Employee(const Employee& E) { lastName = E.lastName; firstName = E.firstName; idNumber = E.idNumber; salary = E.salary; } //-------------------------- operator= --------------------------------------- Employee& Employee::operator=(const Employee& E) { if (&E != this) { idNumber = E.idNumber; salary = E.salary; lastName = E.lastName; firstName = E.firstName; } return *this; } //----------------------------- setData ------------------------------------ // set data from file bool Employee::setData(ifstream& inFile) { inFile >> lastName >> firstName >> idNumber >> salary; return idNumber >= 0 && idNumber <= MAXID && salary >= 0; } //------------------------------- < ---------------------------------------- // < defined by value of name bool Employee::operator<(const Employee& E) const { return lastName < E.lastName || (lastName == E.lastName && firstName < E.firstName); } //------------------------------- <= ---------------------------------------- // < defined by value of inamedNumber bool Employee::operator<=(const Employee& E) const { return *this < E || *this == E; } //------------------------------- > ---------------------------------------- // > defined by value of name bool Employee::operator>(const Employee& E) const { return lastName > E.lastName || (lastName == E.lastName && firstName > E.firstName); } //------------------------------- >= ---------------------------------------- // < defined by value of name bool Employee::operator>=(const Employee& E) const { return *this > E || *this == E; } //----------------- operator == (equality) ---------------- // if name of calling and passed object are equal, // return true, otherwise false // bool Employee::operator==(const Employee& E) const { return lastName == E.lastName && firstName == E.firstName; } //----------------- operator != (inequality) ---------------- // return opposite value of operator== bool Employee::operator!=(const Employee& E) const { return !(*this == E); } //------------------------------- << --------------------------------------- // display Employee object ostream& operator<<(ostream& output, const Employee& E) { output << setw(4) << E.idNumber << setw(7) << E.salary << " " << E.lastName << " " << E.firstName << endl; return output; } I will include a check for NULL pointer but I just want to get this working and will test it on a list that includes the data I am checking. Thanks to whoever can help and as usual, this is for a course so I don't expect or want the answer, but any tips as to what might be going wrong will help immensely!

    Read the article

  • How do I process a nested list?

    - by ddbeck
    Suppose I have a bulleted list like this: * list item 1 * list item 2 (a parent) ** list item 3 (a child of list item 2) ** list item 4 (a child of list item 2 as well) *** list item 5 (a child of list item 4 and a grand-child of list item 2) * list item 6 I'd like to parse that into a nested list or some other data structure which makes the parent-child relationship between elements explicit (rather than depending on their contents and relative position). For example, here's a list of tuples containing an item and a list of its children (and so forth): [('list item 1',), ('list item 2', [('list item 3',), [('list item 4', [('list item 5'),]] ('list item 6',)] I've attempted to do this with plain Python and some experimentation with Pyparsing, but I'm not making progress. I'm left with two major questions: What's the strategy I need to employ to make this work? I know recursion is part of the solution, but I'm having a hard time making the connection between this and, say, a Fibonacci sequence. I'm certain I'm not the first person to have done this, but I don't know the terminology of the problem to make fruitful searches for more information on this topic. What problems are related to this so that I can learn more about solving these kinds of problems in general?

    Read the article

  • Linked List Inserting in sorted format

    - by user2738718
    package practise; public class Node { public int data; public Node next; public Node (int data, Node next) { this.data = data; this.next = next; } public int size (Node list) { int count = 0; while(list != null){ list = list.next; count++; } return count; } public static Node insert(Node head, int value) { Node T; if (head == null || head.data <= value) { T = new Node(value,head); return T; } else { head.next = insert(head.next, value); return head; } } } This work fine for all data values less than the first or the head. anything greater than than doesn't get added to the list.please explain in simple terms thanks.

    Read the article

  • Linked list recursive reverse

    - by Phoenix
    I was looking at the code below from stanford library: void recursiveReverse(struct node** head_ref) { struct node* first; struct node* rest; /* empty list */ if (*head_ref == NULL) return; /* suppose first = {1, 2, 3}, rest = {2, 3} */ first = *head_ref; rest = first->next; /* List has only one node */ if (rest == NULL) return; /* put the first element on the end of the list */ recursiveReverse(&rest); first->next->next = first; /* tricky step -- see the diagram */ first->next = NULL; /* fix the head pointer */ *head_ref = rest; } What I don't understand is in the last recursive step for e.g if list is 1-2-3-4 Now for the last recursive step first will be 1 and rest will be 2. So if you set *head_ref = rest .. that makes the head of the list 2 ?? Can someone please explain how after reversing the head of the list becomes 4 ??

    Read the article

  • cannot delete from doubly linked list using visual studios in C

    - by Jesus Sanchez
    hello I am currently doing an assignment that is supposed to read in a file, use the information, and then print out another file. all using doubly linked list. Currently i am trying to just read in the file into a doubly linked list, print it out onto the screen and a file, and finally delete the list and close the program. The program works fine as long as I don't call the dlist_distroy function which is supposed to delete the string. as soon as I do it the program starts running and then a window pops up saying "Windows has triggered a breakpoint in tempfilter.exe. This may be due to a corruption of the heap, which indicates a bug in tempfilter.exe or any of the DLLs it has loaded. This may also be due to the user pressing F12 while tempfilter.exe has focus. The output window may have more diagnostic information." I have revised the destroy and remove functions and cant understand the problem. my program is the following main.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include "dlinklist.h" #include "DlistElmt.h" #include "Dlist.h" #include "dlistdata.h" /**************************************************************************************************/ int main ( int argc, char *argv[] ) { FILE *ifp, *ofp; int hour, min; Dlist *list; DlistElmt *current=NULL, *element; float temp; list = (Dlist *)malloc(sizeof(list)); element = (DlistElmt *)malloc(sizeof(element)); if ( argc != 3 ) /* argc should be 3 for correct execution */ { /* We print argv[0] assuming it is the program name */ /* TODO: This is wrong, it should be: usage: %s inputfile outputfile */ printf( "usage: %s filename", argv[0] ); } else { // We assume argv[1] is a filename to open ifp = fopen( argv[1], "r" ); if (ifp == 0 ){ printf("Could not open file\n"); } else{ ofp = fopen(argv[2], "w"); dlist_init(list);//, (destroy)(hour, min, temp)); while (fscanf(ifp, "%d:%d %f ", &hour, &min, &temp) == 3) { current=list->tail; if(dlist_size(list)==0){ dlist_ins_prev(list, current, hour, min, temp); } else{ dlist_ins_next(list, current, hour, min, temp); } } current = list->head; while(current != NULL){ if(current==list->head){ current=current->next; } else if((current->temp > (current->prev->temp +5)) || (current->temp < (current->prev->temp -5))){ dlist_remove(list, current); current=current->next; } else current=current->next; } current = list->head; while(current != NULL){ printf("%d:%d %2.1lf\n" ,current->time, current->time2, current->temp ); fprintf(ofp, "%d:%d %2.1lf\n", current->time, current->time2, current->temp ); current = current->next; } //dlist_destroy(list); //} fclose(ifp); fclose(ofp); } } getchar(); } dlistdata.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include "dlinklist.h" #include "DlistElmt.h" #include "dlistdata.h" /**************************************************************************************************/ void dlist_init(Dlist *list){ list->size = 0; list->head = NULL; list->tail = NULL; return; } void dlist_destroy(Dlist *list){ while (dlist_size(list) > 0){ dlist_remove(list, list->head); } memset(list, 0, sizeof(Dlist)); return; } int dlist_ins_next(Dlist *list, DlistElmt *element, const int time, const int time2, const float temp){ DlistElmt *new_element; if (element == NULL && dlist_size(list) != 0) return -1; if ((new_element = (DlistElmt *)malloc(sizeof(new_element))) == NULL) return -1; new_element->time = (int )time; new_element->time2 = (int )time2; new_element->temp = (float )temp; if (dlist_size(list) == 0) { list->head = new_element; list->head->prev = NULL; list->head->next = NULL; list->tail = new_element; } else { new_element->next = element->next; new_element->prev = element; if(element->next == NULL) list->tail = new_element; else element->next->prev = new_element; element->next = new_element; } list->size++; return 0; } int dlist_ins_prev(Dlist *list, DlistElmt *element, const int time, const int time2, const float temp){ DlistElmt *new_element; if (element == NULL && dlist_size(list) != 0) return -1; if ((new_element = (DlistElmt *)malloc(sizeof(new_element))) == NULL) return -1; new_element->time = (int )time; new_element->time2 = (int )time2; new_element->temp = (float )temp; if (dlist_size(list) == 0){ list->head = new_element; list->head->prev = NULL; list->head->next=NULL; list->tail = new_element; } else{ new_element->next = element; new_element->prev = element->prev; if(element->prev ==NULL) list->head = new_element; else element->prev->next = new_element; element->prev = new_element; } list->size++; return 0; } int dlist_remove(Dlist *list, DlistElmt *element){//, int time, int time2, float temp){ if (element == NULL || dlist_size(list) == 0) return -1; if (element == list->head) { list->head = element->next; if (list->head == NULL) list->tail = NULL; else element->next->prev = NULL; } else{ element->prev->next = element->next; if (element->next = NULL) list->tail = element->prev; else element->next->prev = element->prev; } free(element); list->size--; return 0; }

    Read the article

  • Top 10 Linked Blogs of 2010

    - by Bill Graziano
    Each week I send out a SQL Server newsletter and include links to interesting blog posts.  I’ve linked to over 500 blog posts so far in 2010.  Late last year I started storing those links in a database so I could do a little reporting.  I tend to link to posts related to the OLTP engine.  I also try to link to the individual blogger in the group blogs.  Unfortunately that wasn’t possible for the SQLCAT and CSS blogs.  I also have a real weakness for posts related to PASS. These are the top 10 blogs that I linked to during the year ordered by the number of posts I linked to. Paul Randal – Paul writes extensively on the internals of the relational engine.  Lots of great posts around transactions, transaction log, disaster recovery, corruption, indexes and DBCC.  I also linked to many of his SQL Server myths posts. Glenn Berry – Glenn writes very interesting posts on how hardware affects SQL Server.  I especially like his posts on the various CPU platforms.  These aren’t necessarily topics that I’m searching for but I really enjoy reading them. The SQLCAT Team – This Microsoft team focuses on the largest and most interesting SQL Server installations.  The regularly publish white papers and best practices. SQL Server CSS Team – These are the top engineers from the Microsoft Customer Service and Support group.  These are the folks you finally talk to after your case has been escalated about 20 times.  They write about the interesting problems they find. Brent Ozar – The posts I linked to mostly focused on the relational engine: CPU, NUMA, SSD drives, performance monitoring, etc.  But Brent writes about a real variety of topics including blogging, social networking, speaking, the MCM, SQL Azure and anything else that seems to strike his fancy.  His posts are always well written and though provoking. Jeremiah Peschka – A number of Jeremiah’s posts weren’t about SQL Server.  He’s very active in the “NoSQL” area and I linked to a number of those posts.  I think it’s important for people to know what other technologies are out there. Brad McGehee – Brad writes about being a DBA including maintenance plans, DBA checklists, compression and audit. Thomas LaRock – I linked to a variety of posts from PBM to networking to 24 Hours of PASS to TDE.  Just a real variety of topics.  Tom always writes with an interesting style usually mixing in a movie theme and/or bacon. Aaron Bertrand – Many of my links this year were Denali features.  He also had a great series on bad habits to kick. Michael J. Swart – This last one surprised me.  There are some well known SQL Server bloggers below Michael on this list.  I linked to posts on indexes, hierarchies, transactions and I/O performance and a variety of other engine related posts.  All are interesting and well thought out.  Many of his non-SQL posts are also very good.  He seems to have an interest in puzzles and other brain teasers.  Michael, I won’t be surprised again!

    Read the article

  • Haskell - function (that returns a list) on each element in a list

    - by Ben
    The assignment is to create a multiples function and I essentially want todo the following code: map (\t -> scanl (\x y -> x+y) t (repeat t)) listofnumbers The problem is that the scanl function returns a list of results rather than the one which the map function requires. So is there a function that will allow the return of lists?

    Read the article

  • Random List of numbers in C

    - by Ant
    I have just started a C programming course and so far have only done the basics like printf, read a little on variables etc on the course book. The teacher has tasked us with writing a program that will take a value entered by the user, this will be the number of students in the class (25 at the moment but can be variable). It will then list the number of students randomly and place them in 3 columns. The purpose is to sort students into groups of 3 randomly, then display on the screen in columns. Now my question is not for the code that defeats the object of me attempting the exercise, but how to structure it. I can see that using an array can be used to display the list, but really after some pointers on how best to approach the problem in blocks, then I can attempt to program each block.

    Read the article

  • trying to append a list, but something breaks

    - by romunov
    I'm trying to create an empty list which will have as many elements as there are num.of.walkers. I then try to append, to each created element, a new sub-list (length of new sub-list corresponds to a value in a. When I fiddle around in R everything goes smooth: list.of.dist[[1]] <- vector("list", a[1]) list.of.dist[[2]] <- vector("list", a[2]) list.of.dist[[3]] <- vector("list", a[3]) list.of.dist[[4]] <- vector("list", a[4]) I then try to write a function. Here is my feeble attempt that results in an error. Can someone chip in what am I doing wrong? countNumberOfWalks <- function(walk.df) { list.of.walkers <- sort(unique(walk.df$label)) num.of.walkers <- length(unique(walk.df$label)) #Pre-allocate objects for further manipulation list.of.dist <- vector("list", num.of.walkers) a <- c() # Count the number of walks per walker. for (i in list.of.walkers) { a[i] <- nrow(walk.df[walk.df$label == i,]) } a <- as.vector(a) # Add a sublist (length = number of walks) for each walker. for (i in i:num.of.walkers) { list.of.dist[[i]] <- vector("list", a[i]) } return(list.of.dist) } > num.of.walks.per.walker <- countNumberOfWalks(walk.df) Error in vector("list", a[i]) : vector size cannot be NA

    Read the article

  • Linked servers SQLNCLI problem. "No transaction is active"

    - by Felipe Fiali
    Im trying to execute a stored procedure and simply insert its results in a temporary table, and I'm getting the following message: The operation could not be performed because OLE DB provider "SQLNCLI" for linked server "MyServerName" was unable to begin a distributed transaction. OLE DB provider "SQLNCLI" for linked server "MyServerName" returned message "No transaction is active.". My query looks like this: INSERT INTO #TABLE EXEC MyServerName.MyDatabase.dbo.MyStoredProcedure Param1, Param2, Param3 Exact column number, names, the problem is not the result. MSDTC is allowed and started in both computers, Remote procedure calling too. The machines are not in the same domain, but I can execute remote queries from my machine and get the result. I can even execute the stored procedure and see its results, I just can't insert it in another table. Help, please? :)

    Read the article

  • How to optimize simple linked server select query?

    - by tomaszs
    Hello, I have a table called Table with columns: ID (int, primary key, clustered, unique index) TEXT (varchar 15) on a MSSQL linked server called LS. Linked server is on the same server computer. And: When I call: SELECT ID, TEXT FROM OPENQUERY(LS, 'SELECT ID, TEXT FROM Table') It takes 400 ms. When I call: SELECT ID, TEXT FROM LS.dbo.Table It takes 200 ms And when I call the query directly while being at LS server: SELECT ID, TEXT FROM dbo.Table It takes 100 ms. In many places i've read that OPENQUERY is faster, but in this simple case it does not seem to work. What can I do to make this query faster when I call it from another server, not LS directly?

    Read the article

  • Linked List Sorting with Strings In C

    - by user308583
    I have a struct, with a Name and a single Node called nextName It's a Singly Linked list, and my task is to create the list, based on alphabetical order of the strings. So iff i enter Joe Zolt and Arthur i should get my list structured as Joe Than Joe Zolt Than Arthur Joe Zolt I'm having trouble implementing the correct Algorithm, which would put the pointers in the right order. This is What I have as of Now. Temp would be the name the user just entered and is trying to put into the list, namebox is just a copy of my root, being the whole list if(temp != NULL) { struct node* namebox = root; while (namebox!=NULL && (strcmp((namebox)->name,temp->name) <= 0)) { namebox = namebox->nextName; printf("here"); } temp->nextName = namebox; namebox = temp; root = namebox; This Works right now, if i enter names like CCC BBB than AAA I Get Back AAA BBB CCC when i print But if i put AAA BBB CCC , When i print i only get CCC, it cuts the previous off.

    Read the article

  • Using FindAll on a List<List<T>> type

    - by Ken Foster
    Assuming public class MyClass { public int ID {get; set; } public string Name {get; set; } } and List<MyClass> classList = //populate with MyClass instances of various IDs I can do List<MyClass> result = classList.FindAll(class => class.ID == 123); and that will give me a list of just classes with ID = 123. Works great, looks elegant. Now, if I had List<List<MyClass>> listOfClassLists = //populate with Lists of MyClass instances How do I get a filtered list where the lists themselves are filtered. I tried List<List<MyClass>> result = listOfClassLists.FindAll (list => list.FindAll(class => class.ID == 123).Count > 0); it looks elegant, but doesn't work. It only includes Lists of classes where at least one class has an ID of 123, but it includes ALL MyClass instances in that list, not just the ones that match. I ended up having to do List<List<MyClass>> result = Results(listOfClassLists, 123); private List<List<MyClass>> Results(List<List<MyClass>> myListOfLists, int id) { List<List<MyClass>> results = new List<List<MyClass>>(); foreach (List<MyClass> myClassList in myListOfLists) { List<MyClass> subList = myClassList.FindAll(myClass => myClass.ID == id); if (subList.Count > 0) results.Add(subList); } return results; } which gets the job done, but isn't that elegant. Just looking for better ways to do a FindAll on a List of Lists. Ken

    Read the article

  • Query through linked server is very slow

    - by Sergey Olontsev
    I have 2 SQL 2005 servers SRV1 and SRV2. SRV2 is the linked server on SRV1. I run a storep proc with params on SRV2 and it is completed immediately. But when I run the same proc through the linked server on SRV1, for example EXEC [SRV1].DB_TEST.dbo.p_sample_proc it takes about 8-10 minutes to complete. After restarting SRV2 the problem is gone. But some time later it returns. Does anyone have any ideas what it could be?

    Read the article

  • Unique elements of list within list in python

    - by user2901061
    We are given a list of animals in different zoos and need to find which zoos have animals that are not in any others. The animals of each zoo are separated by spaces, and each zoo is originally separated by a comma. I am currently enumerating over all of the zoos to split each animal and create lists within lists for different zoos as such: for i, zoo in enumerate(zoos): zoos[i] = zoo.split() However, I then do not know how to tell and count how many of the zoos have unique animals. I figure it is something else with enumerate and possibly sets, but cannot get it down exactly. Any help is greatly appreciated. Thanks

    Read the article

  • Optimizing list comprehension to find pairs of co-prime numbers

    - by user3685422
    Given A,B print the number of pairs (a,b) such that GCD(a,b)=1 and 1<=a<=A and 1<=b<=B. Here is my answer: return len([(x,y) for x in range(1,A+1) for y in range(1,B+1) if gcd(x,y) == 1]) My answer works fine for small ranges but takes enough time if the range is increased. such as 1 <= A <= 10^5 1 <= B <= 10^5 is there a better way to write this or can this be optimized?

    Read the article

  • C++ stl collections or linked lists

    - by Lucas
    I'm developing a OpenGL based simulation in C++. I'm optmizing my code now and i see throughout the code the frequently use of std:list and std:vector. What is the more performatic: to continue using C++ stl data structs or a pointer based linked list? The main operation that involve std::list and std::vector is open a iterator and loop through all items in the data structs and apply some processing

    Read the article

  • Adding nodes to a global linked-list

    - by Zack
    I am attempting to construct my first linked list, and having read a basic introduction, have done the following. Firstly, declare a linked list node as: struct errorNode { uint8 error; struct errorNode* next; }; Secondly, define the first node globally as: struct errorNode errorList = {0, NULL}; This has been done to allow each of the libraries that make up my current project to insert errors into a common list. The function to do this is: void errorListWrite(uint8 error) { struct errorNode* newNode = malloc(sizeof(struct errorNode)); newNode->error = error; newNode->next = &errorList; errorList = *newNode; } Whilst this compiles without error, it does not function as expected. I thnk the problem is with the last two statements of the list write function, but I am unsure. A hint as to what I am doing wrong would be most appreciated.

    Read the article

  • Building a linked list with LINQ

    - by FreshCode
    What is the fastest way to order an unordered list of elements by predecessor (or parent) element index using LINQ? Each element has a unique ID and the ID of that element's predecessor (or parent) element, from which a linked list can be built to represent an ordered state. Example ID | Predecessor's ID --------|-------------------- 20 | 81 81 | NULL 65 | 12 12 | 20 120 | 65 The sorted order is {81, 20, 12, 65, 120}. An (ordered) linked list can easily be assembled iteratively from these elements, but can it be done in fewer LINQ statements? Edit: I should have specified that IDs are not necessarily sequential. I chose 1 to 5 for simplicity. See updated element indices which are random.

    Read the article

  • concurrent doubly-linked list (1 writer, n-readers)

    - by Arne
    Hi guys, I am back in the field of programming for my Diploma-thesis now and stumbled over the following issue: I need to implement a thread-safe doubly-linked list for one thread writing the list at any position (delete, insert, mutate node data) and one to many threads traversing and reading the list. I am well aware that mutexes can be used to serialize access to the list, still I presume that a naive lock around any write operation will be less than optimal. I am wondering whether there are better variants. (I am well aware that 'optimal' has not much of a practical meaning as long as no exact measure/profiling are available but this is an academic thesis after all..) I am very gratefull for code-samples as well as references to academic granted these have at least a tiny bit of practical relevance. Thanks at lot

    Read the article

  • Linked List exercise, what am I doing wrong?

    - by Sean Ochoa
    Hey all. I'm doing a linked list exercise that involves dynamic memory allocation, pointers, classes, and exceptions. Would someone be willing to critique it and tell me what I did wrong and what I should have done better both with regards to style and to those subjects I listed above? /* Linked List exercise */ #include <iostream> #include <exception> #include <string> using namespace std; class node{ public: node * next; int * data; node(const int i){ data = new int; *data = i; } node& operator=(node n){ *data = *(n.data); } ~node(){ delete data; } }; class linkedList{ public: node * head; node * tail; int nodeCount; linkedList(){ head = NULL; tail = NULL; } ~linkedList(){ while (head){ node* t = head->next; delete head; if (t) head = t; } } void add(node * n){ if (!head) { head = n; head->next = NULL; tail = head; nodeCount = 0; }else { node * t = head; while (t->next) t = t->next; t->next = n; n->next = NULL; nodeCount++; } } node * operator[](const int &i){ if ((i >= 0) && (i < nodeCount)) throw new exception("ERROR: Invalid index on linked list.", -1); node *t = head; for (int x = i; x < nodeCount; x++) t = t->next; return t; } void print(){ if (!head) return; node * t = head; string collection; cout << "["; int c = 0; if (!t->next) cout << *(t->data); else while (t->next){ cout << *(t->data); c++; if (t->next) t = t->next; if (c < nodeCount) cout << ", "; } cout << "]" << endl; } }; int main (const int & argc, const char * argv[]){ try{ linkedList * myList = new linkedList; for (int x = 0; x < 10; x++) myList->add(new node(x)); myList->print(); }catch(exception &ex){ cout << ex.what() << endl; return -1; } return 0; }

    Read the article

  • Generic linked list in c++

    - by itsaboy
    I have been struggling for too long a time now with a rather simple question about how to create a generic linked list in c++. The list should be able contain several types of structs, but each list will only contain one type of struct. The problem arises when I want to implement the getNode() function [see below], because then I have to specify which of the structs it should return. I have tried to substitute the structs with classes, where the getNode function returns a base class that is inherited by all the other classes, but it still does not do the trick, since the compiler does not allow the getNode function to return anything but the base class then. So here is some code snippet: typedef struct struct1 { int param1; (...) } struct1; typedef struct struct2 { double param1; (...) } struct2; typedef struct node { struct1 data; node* link; } node; class LinkedList { public: node *first; int nbrOfNodes; LinkedList(); void addNode(struct1); struct1 getNode(); bool isEmpty(); }; LinkedList::LinkedList() { first = NULL; nbrOfNodes = 0; } void LinkedList::addNode(struct1 newData) { if (nbrOfNodes == 0) { first = new node; first->data = newData; } else { node *it = first; for (int i = 0; i < nbrOfNodes; i++) { it = it->link; } node *newNode = new node; newNode->data = newData; it->link = newNode; } nbrOfNodes++; } bool LinkedList::isEmpty() { return !nbrOfNodes; } struct1 LinkedList::getNode() { param1 returnData = first->data; node* deleteNode = first; nbrOfNodes--; if (nbrOfNodes) first = deleteNode->link; delete deleteNode; return returnData; } So the question, put in one sentence, is as follows: How do I adjust the above linked list class so that it can also be used for struct2, without having to create a new almost identical list class for struct2 objects? As I said above, each instance of LinkedList will only deal with either struct1 or struct2. Grateful for hints or help

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >