Search Results

Search found 137626 results on 5506 pages for 'linked lists using c'.

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

  • Problems with Linked List in C

    - by seePhor
    Hey everyone, I am new to C and I am working on an XOR linked list for a project. I have most of the code done, but I can't seem to get the delete function of the list to work properly. It seems able to delete some numbers, but not any number you pass into the function. Could anyone experienced with C take a look and possibly point out where I went wrong? I have been working on this for a while now and have not had much luck and I have started over 3 times :( Any help is much appreciated. Thank you. You can see my first attempt of code here. I can only post one link, so if you would like to see my second attempt, just tell me so and I can email it to you or something. Thank you for your time.

    Read the article

  • Reworking my singly linked list

    - by Stradigos
    Hello everyone, thanks for taking the time to stop by my question. Below you will find my working SLL, but I want to make more use of C# and, instead of having two classes, SLL and Node, I want to use Node's constructors to do all the work (To where if you pass a string through the node, the constructor will chop it up into char nodes). The problem is, after an a few hours of tinkering, I'm not really getting anywhere... using System; using System.Collections.Generic; using System.Text; using System.IO; namespace PalindromeTester { class Program { static void Main(string[] args) { SLL mySLL = new SLL(); mySLL.add('a'); mySLL.add('b'); mySLL.add('c'); mySLL.add('d'); mySLL.add('e'); mySLL.add('f'); Console.Out.WriteLine("Node count = " + mySLL.count); mySLL.reverse(); mySLL.traverse(); Console.Out.WriteLine("\n The header is: " + mySLL.gethead); Console.In.ReadLine(); } class Node { private char letter; private Node next; public Node() { next = null; } public Node(char c) { this.data = c; } public Node(string s) { } public char data { get { return letter; } set { letter = value; } } public Node nextNode { get { return next; } set { next = value; } } } class SLL { private Node head; private int totalNode; public SLL() { head = null; totalNode = 0; } public void add(char s) { if (head == null) { head = new Node(); head.data = s; } else { Node temp; temp = new Node(); temp.data = s; temp.nextNode = head; head = temp; } totalNode++; } public int count { get { return totalNode; } } public char gethead { get { return head.data; } } public void traverse() { Node temp = head; while(temp != null) { Console.Write(temp.data + " "); temp = temp.nextNode; } } public void reverse() { Node q = null; Node p = this.head; while(p!=null) { Node r=p; p=p.nextNode; r.nextNode=q; q=r; } this.head = q; } } } } Here's what I have so far in trying to work it into Node's constructors: using System; using System.Collections.Generic; using System.Text; using System.IO; namespace PalindromeTester { class Program { static void Main(string[] args) { //Node myList = new Node(); //TextReader tr = new StreamReader("data.txt"); //string line; //while ((line = tr.ReadLine()) != null) //{ // Console.WriteLine(line); //} //tr.Close(); Node myNode = new Node("hello"); Console.Out.WriteLine(myNode.count); myNode.reverse(); myNode.traverse(); // Console.Out.WriteLine(myNode.gethead); Console.In.ReadLine(); } class Node { private char letter; private Node next; private Node head; private int totalNode; public Node() { head = null; totalNode = 0; } public Node(char c) { if (head == null) { head = new Node(); head.data = c; } else { Node temp; temp = new Node(); temp.data = c; temp.nextNode = head; head = temp; } totalNode++; } public Node(string s) { foreach (char x in s) { new Node(x); } } public char data { get { return letter; } set { letter = value; } } public Node nextNode { get { return next; } set { next = value; } } public void reverse() { Node q = null; Node p = this.head; while (p != null) { Node r = p; p = p.nextNode; r.nextNode = q; q = r; } this.head = q; } public void traverse() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.nextNode; } } public int count { get { return totalNode; } } } } } Ideally, the only constructors and methods I would be left with are Node(), Node(char c), Node(string s), Node reserve() and I'll be reworking traverse into a ToString overload. Any suggestions?

    Read the article

  • C++ Memory Allocation & Linked List Implementation

    - by pws5068
    I'm writing software to simulate the "first-fit" memory allocation schema. Basically, I allocate a large X megabyte chunk of memory and subdivide it into blocks when chunks are requested according to the schema. I'm using a linked list called "node" as a header for each block of memory (so that we can find the next block without tediously looping through every address value. head_ptr = (char*) malloc(total_size + sizeof(node)); if(head_ptr == NULL) return -1; // Malloc Error .. :-( node* head_node = new node; // Build block header head_node->next = NULL; head_node->previous = NULL; // Header points to next block (which doesn't exist yet) memset(head_ptr,head_node, sizeof(node)); ` But this last line returns: error: invalid conversion from 'node*' to 'int' I understand why this is invalid.. but how can I place my node into the pointer location of my newly allocated memory?

    Read the article

  • C++ Linked List - Reading data from a file with a sentinel

    - by Nick
    So I've done quite a bit of research on this and can't get my output to work correctly. I need to read in data from a file and have it stored into a Linked List. The while loop used should stop once it hits the $$$$$ sentinel. Then I am to display the data (by searching by ID Number[user input]) I am not that far yet I just want to properly display the data and get it read in for right now. My problem is when it displays the data is isn't stopping at the $$$$$ (even if I do "inFile.peek() != EOF and omit the $$$$$) I am still getting an extra garbage record. I know it has something to do with my while loop and how I am creating a new Node but I can't get it to work any other way. Any help would be appreciated. students.txt Nick J Cooley 324123 60 70 80 90 Jay M Hill 412254 70 80 90 100 $$$$$ assign6.h file #pragma once #include <iostream> #include <string> using namespace std; class assign6 { public: assign6(); // constructor void displayStudents(); private: struct Node { string firstName; string midIni; string lastName; int idNum; int sco1; //Test score 1 int sco2; //Test score 2 int sco3; //Test score 3 int sco4; //Test score 4 Node *next; }; Node *head; Node *headPtr; }; assign6Imp.cpp // Implementation File #include "assign6.h" #include <fstream> #include <iostream> #include <string> using namespace std; assign6::assign6() //constructor { ifstream inFile; inFile.open("students.txt"); head = NULL; head = new Node; headPtr = head; while (inFile.peek() != EOF) //reading in from file and storing in linked list { inFile >> head->firstName >> head->midIni >> head->lastName; inFile >> head->idNum; inFile >> head->sco1; inFile >> head->sco2; inFile >> head->sco3; inFile >> head->sco4; if (inFile != "$$$$$") { head->next = NULL; head->next = new Node; head = head->next; } } head->next = NULL; inFile.close(); } void assign6::displayStudents() { int average = 0; for (Node *cur = headPtr; cur != NULL; cur = cur->next) { cout << cur->firstName << " " << cur->midIni << " " << cur->lastName << endl; cout << cur->idNum << endl; average = (cur->sco1 + cur->sco2 + cur->sco3 + cur->sco4)/4; cout << cur->sco1 << " " << cur->sco2 << " " << cur->sco3 << " " << cur->sco4 << " " << "average: " << average << endl; } }

    Read the article

  • recursively reverse linked list.

    - by Amanda
    I am implementing a function to recursively reverse a linked-list, but getting seg-fault. typedef struct _node { int data; struct _node *next; } Node, *NodeP; NodeP recursiveReverseList(NodeP first){ if(first == NULL) return NULL; if(first->next == NULL) return head; NodeP rest = recursiveReverseList(head->next); rest->next = first; first->next = NULL; return first; } Can you please help. P.S. The iterative version is working fine though. Its not homework. Just practicing C.

    Read the article

  • Linked List. Insert integers in order

    - by user69514
    I have a linked list of integers. When I insert a new Node I need to insert it not at the end, but in oder... i.e. 2, 4, 5, 8, 11, 12, 33, 55, 58, 102, etc. I don't think I am inserting it in the correct position. Do see what Im doing wrong? Node newNode = new Node(someInt); Node current = head; for(int i=0; i<count; i++){ if(current == tail && tail.data < someInt){ tail.next = newNode; } if(current.data < someInt && current.next.data >= someInt){ newNode.next = current.next; current.next = newNode; } }

    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

  • Conditional jump or move depends on uninitialised value - freeing a linked list

    - by user720491
    I want to free a linked list in C. All is working fine, but Valgrind is telling me Conditional jump or move depends on uninitialised value(s) at 0x401400: mtf_destroy Here's the code: list_elt *head; void mtf_init() { list_elt *current; head = malloc(sizeof(list_elt)); current = head; for (int i = 0; i < LIST_SIZE-1; i++) { current->value = (BYTE) i; current->next = malloc(sizeof(list_elt)); current = current->next; } current->value = LIST_SIZE-1; } void mtf_destroy(list_elt *elt) { if (elt->next != NULL) mtf_destroy(elt->next); free(elt); } How can I solve this? Thanks!

    Read the article

  • setting up linked list Java

    - by erp
    I'm working on some basic linked list stuff, like insert, delete, go to the front or end of the list, and basically i understand the concept of all of that stuff once i have the list i guess but im having trouble setting up the list. I was wondering of you guys could tell me if im going in the right direction. (mostly just the setup) this is what i have so far: public class List { private int size; private List linkedList; List head; List cur; List next; /** * Creates an empty list. * @pre * @post */ public List(){ linkedList = new List(); this.head = null; cur = head; } /** * Delete the current element from this list. The element after the deleted element becomes the new current. * If that's not possible, then the element before the deleted element becomes the new current. * If that is also not possible, then you need to recognize what state the list is in and define current accordingly. * Nothing should be done if a delete is not possible. * @pre * @post */ public void delete(){ // delete size--; } /** * Get the value of the current element. If this is not possible, throw an IllegalArgumentException. * @pre the list is not empty * @post * @return value of the current element. */ public char get(){ return getItem(cur); } /** * Go to the last element of the list. If this is not possible, don't change the cursor. * @pre * @post */ public void goLast(){ while (cur.next != null){ cur = cur.next; } } /** * Advance the cursor to the next element. If this is not possible, don't change the cursor. * @pre * @post */ public void goNext(){ if(cur.next != null){ cur = cur.next;} //else do nothing } /** * Retreat the cursor to the previous element. If this is not possible, don't change the cursor. * @pre * @post */ public void goPrev(){ } /** * Go to top of the list. This is the position before the first element. * @pre * @post */ public void goTop(){ } /** * Go to first element of the list. If this is not possible, don't change the cursor. * @pre * @post */ public void goFirst(){ } /** * Insert the given parameter after the current element. The newly inserted element becomes the current element. * @pre * @post * @param newVal : value to insert after the current element. */ public void insert(char newVal){ cur.setItem(newVal); size++; } /** * Determines if this list is empty. Empty means this list has no elements. * @pre * @post * @return true if the list is empty. */ public boolean isEmpty(){ return head == null; } /** * Determines the size of the list. The size of the list is the number of elements in the list. * @pre * @post * @return size which is the number of elements in the list. */ public int size(){ return size; } public class Node { private char item; private Node next; public Node() { } public Node(char item) { this.item = item; } public Node(char item, Node next) { this.item = item; this.next = next; } public char getItem() { return this.item; } public void setItem(char item) { this.item = item; } public Node getNext() { return this.next; } public void setNext(Node next) { this.next = next; } } } I got the node class alright (well i think it works alright), but is it necessary to even have that class? or can i go about it without even using it (just curious). And for example on the method get() in the list class can i not call that getItem() method from the node class because it's getting an error even though i thought that was the whole point for the node class. bottom line i just wanna make sure im setting up the list right. Thanks for any help guys, im new to linked list's so bear with me!

    Read the article

  • Iterators over a LInked List in a Game in Java

    - by Matthew
    I am using OpenGl in android and they have a callback method called draw that gets called with out my control. (As fast as the device can handle if I am not mistaken) I have a list of "GameObjects" that have a .draw method and a .update method. I have two different threads that handle each of those. So, the question is, can I declare two different iterators in two different methods in two different threads that iterate over the same Linked List? If so, do I simply declare ListIterator<GameObject> l = objets.listIterator() each time I want a new iterator and it won't interfere with other iterators?

    Read the article

  • Reversing linked list C

    - by user2976389
    node *rever(node *root) { node *prev = NULL; node *xnew = NULL; while (root != NULL) { xnew = malloc(sizeof(root)); xnew->value = root->value; xnew->next = prev; prev = xnew; root = root->next; } return xnew; } Hello I wrote this linked list reverse function. However it doesn't work(empty response): I suspect it's because of prev index getting overwritten. Could someone explain me whats going on? I know I could find working code on the internet but I wanna know what am I doing wrong. Thanks

    Read the article

  • 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

  • Faster way to transfer table data from linked server

    - by spender
    After much fiddling, I've managed to install the right ODBC driver and have successfully created a linked server on SQL Server 2008, by which I can access my PostgreSQL db from SQL server. I'm copying all of the data from some of the tables in the PgSQL DB into SQL Server using merge statements that take the following form: with mbRemote as ( select * from openquery(someLinkedDb,'select * from someTable') ) merge into someTable mbLocal using mbRemote on mbLocal.id=mbRemote.id when matched /*edit*/ /*clause below really speeds things up when many rows are unchanged*/ /*can you think of anything else?*/ and not (mbLocal.field1=mbRemote.field1 and mbLocal.field2=mbRemote.field2 and mbLocal.field3=mbRemote.field3 and mbLocal.field4=mbRemote.field4) /*end edit*/ then update set mbLocal.field1=mbRemote.field1, mbLocal.field2=mbRemote.field2, mbLocal.field3=mbRemote.field3, mbLocal.field4=mbRemote.field4 when not matched then insert ( id, field1, field2, field3, field4 ) values ( mbRemote.id, mbRemote.field1, mbRemote.field2, mbRemote.field3, mbRemote.field4 ) WHEN NOT MATCHED BY SOURCE then delete; After this statement completes, the local (SQL Server) copy is fully in sync with the remote (PgSQL server). A few questions about this approach: is it sane? it strikes me that an update will be run over all fields in local rows that haven't necessarily changed. The only prerequisite is that the local and remote id field match. Is there a more fine grained approach/a way of constraining the merge statment to only update rows that have actually changed?

    Read the article

  • Big problem with Dijkstra algorithm in a linked list graph implementation

    - by Nazgulled
    Hi, I have my graph implemented with linked lists, for both vertices and edges and that is becoming an issue for the Dijkstra algorithm. As I said on a previous question, I'm converting this code that uses an adjacency matrix to work with my graph implementation. The problem is that when I find the minimum value I get an array index. This index would have match the vertex index if the graph vertexes were stored in an array instead. And the access to the vertex would be constant. I don't have time to change my graph implementation, but I do have an hash table, indexed by a unique number (but one that does not start at 0, it's like 100090000) which is the problem I'm having. Whenever I need, I use the modulo operator to get a number between 0 and the total number of vertices. This works fine for when I need an array index from the number, but when I need the number from the array index (to access the calculated minimum distance vertex in constant time), not so much. I tried to search for how to inverse the modulo operation, like, 100090000 mod 18000 = 10000 and, 10000 invmod 18000 = 100090000 but couldn't find a way to do it. My next alternative is to build some sort of reference array where, in the example above, arr[10000] = 100090000. That would fix the problem, but would require to loop the whole graph one more time. Do I have any better/easier solution with my current graph implementation?

    Read the article

  • A queue in C using structs and dynamic memory allocation (linked list)

    - by Martin Pugh
    I am tasked with making a queue data structure in C, as a linked list. Our lecturer gave us a large amount of code to implement a stack, but we have to adapt it to create a queue. The code our lecturer gave us ends up not compiling and segfaulting at the exact same point as the code I wrote for the queue. I'm very new to structs, malloc and C in general, so there could be something painfully obvious I've overlooked. Here is the code I am using: #include <stdio.h> #include <stdlib.h> struct node{ int data; //contains the actual data struct node *prev; //pointer to previous node (Closer to front) struct node *next; //pointer to next node (Closer to back) }; typedef struct node *Nodepointer; struct queue{ Nodepointer front; Nodepointer back; }; typedef struct queue *Queuepointer; main(){ Queuepointer myqueue; //create a queue called myqueue init(myqueue); //initialise the queue Nodepointer new = (Nodepointer)malloc(sizeof(struct node)); myqueue->front = new; } int init(Queuepointer q){ q = (Queuepointer)malloc(sizeof(struct queue)); q->front = NULL; q->back = NULL; } The idea is that the queue struct 'contains' the first and last nodes in a queue, and when a node is created, myqueue is updated. However, I cannot even get to that part (pop and push are written but omitted for brevity). The code is segfaulting at the line myqueue->front = new; with the following gdb output: Program received signal SIGSEGV, Segmentation fault. 0x08048401 in main () at queue.c:27 27 myqueue->front = new; Any idea what I'm doing wrong?

    Read the article

  • sorting names in a linked list

    - by sil3nt
    Hi there, I'm trying to sort names into alphabetical order inside a linked list but am getting a run time error. what have I done wrong here? #include <iostream> #include <string> using namespace std; struct node{ string name; node *next; }; node *A; void addnode(node *&listpointer,string newname){ node *temp; temp = new node; if (listpointer == NULL){ temp->name = newname; temp->next = listpointer; listpointer = temp; }else{ node *add; add = new node; while (true){ if(listpointer->name > newname){ add->name = newname; add->next = listpointer->next; break; } listpointer = listpointer->next; } } } int main(){ A = NULL; string name1 = "bob"; string name2 = "tod"; string name3 = "thomas"; string name4 = "kate"; string name5 = "alex"; string name6 = "jimmy"; addnode(A,name1); addnode(A,name2); addnode(A,name3); addnode(A,name4); addnode(A,name5); addnode(A,name6); while(true){ if(A == NULL){break;} cout<< "name is: " << A->name << endl; A = A->next; } return 0; }

    Read the article

  • linked list sort function only loops once

    - by Tristan Pearce
    i have a singly linked list that i am trying to sort from least to greatest by price. here is what i have so far struct part { char* name; float price; int quantity; struct part *next; }; typedef struct part partType; partType *sort_price(partType **item) { partType *temp1 = *item; partType *temp2 = (*item)->next; if ( *item == NULL || (*item)->next == NULL ) return *item; else { while ( temp2 != NULL && temp2->next != NULL ){ if (temp2->price > temp2->next->price){ temp1->next = temp2->next; temp2->next = temp2->next->next; temp1->next->next = temp2; } temp1 = temp2; temp2 = temp2->next; } } return *item; } the list is already populated but when i call the sort function it only swaps the first two nodes that satisfy the condition in the if statement. I dont understand why it doesnt do the check again after the two temp pointers are incremented.

    Read the article

  • pointer to a pointer in a linked list

    - by user1596497
    I'm trying to set a linked list head through pointer to a pointer. I can see inside the function that the address of the head pointer is changing but as i return to the main progran it becomes NULL again. can someone tell me what I'm doing wrong ?? #include <stdio.h> #include <stdlib.h> typedef void(*fun_t)(int); typedef struct timer_t { int time; fun_t func; struct timer_t *next; }TIMER_T; void add_timer(int sec, fun_t func, TIMER_T *head); void run_timers(TIMER_T **head); void timer_func(int); int main(void) { TIMER_T *head = NULL; int time = 1; fun_t func = timer_func; while (time < 1000) { printf("\nCalling add_timer(time=%d, func=0x%x, head=0x%x)\n", time, func, &head); add_timer(time, func, head); time *= 2; } run_timers(&head); return 0; } void add_timer(int sec, fun_t func, TIMER_T *head) { TIMER_T ** ppScan=&head; TIMER_T *new_timer = NULL; new_timer = (TIMER_T*)malloc(sizeof(TIMER_T)); new_timer->time = sec; new_timer->func = func; new_timer->next = NULL; while((*ppScan != NULL) && (((**ppScan).time)<sec)) ppScan = &(*ppScan)->next; new_timer->next = *ppScan; *ppScan = new_timer; }

    Read the article

  • Linked List Inserting strings in alphabetical order

    - by user69514
    I have a linked list where each node contains a string and a count. my insert method needs to inset a new node in alphabetical order based on the string. if there is a node with the same string, then i increment the count. the problem is that my method is not inserting in alphabetical order public Node findIsertionPoint(Node head, Node node){ if( head == null) return null; Node curr = head; while( curr != null){ if( curr.getValue().compareTo(node.getValue()) == 0) return curr; else if( curr.getNext() == null || curr.getNext().getValue().compareTo(node.getValue()) > 0) return curr; else curr = curr.getNext(); } return null; } public void insert(Node node){ Node newNode = node; Node insertPoint = this.findIsertionPoint(this.head, node); if( insertPoint == null) this.head = newNode; else{ if( insertPoint.getValue().compareTo(node.getValue()) == 0) insertPoint.getItem().incrementCount(); else{ newNode.setNext(insertPoint.getNext()); insertPoint.setNext(newNode); } } count++; }

    Read the article

  • Sequential searching with sorted linked lists

    - by John Graveston
    struct Record_node* Sequential_search(struct Record_node *List, int target) { struct Record_node *cur; cur = List->head ; if(cur == NULL || cur->key >= target) { return NULL; } while(cur->next != NULL) { if(cur->next->key >= target) { return cur; } cur = cur->next; } return cur; } I cannot interpret this pseudocode. Can anybody explain to me how this program works and flows? Given this pseudocode that searches for a value in a linked list and a list that is in an ascending order, what would this program return? a. The largest value in the list that is smaller than target b. The largest value in the list that is smaller than or same as target c. The smallest value in the list that is larger than or same as target d. Target e. The smallest value in the list that is larger than target And say that List is [1, 2, 4, 5, 9, 20, 20, 24, 44, 69, 70, 71, 74, 77, 92] and target 15, how many comparisons are occurred? (here, comparison means comparing the value of target)

    Read the article

  • Adding and sorting a linked list in C

    - by user1202963
    In my assignment, I have to write a function that takes as arguments a pointer to a "LNode" structure and an integer argument. Then, I have to not only add that integer into the linked list, but also put place it so that the list is in proper ascending order. I've tried several various attempts at this, and this is my code as of posting. LNode* AddItem(LNode *headPtr, int newItem) { auto LNode *ptr = headPtr; ptr = malloc(sizeof(LNode)); if (headPtr == NULL) { ptr->value = newItem; ptr->next = headPtr; return ptr; } else { while (headPtr->value > newItem || ptr->next != NULL) { printf("While\n"); // This is simply to let me know how many times the loop runs headPtr = headPtr->next; } ptr->value = newItem; ptr->next = headPtr; return ptr; } } // end of "AddItem" When I run it, and try to insert say a 5 and then a 3, the 5 gets inserted, but then the while loop runs once and I get a segmentation fault. Also I cannot change the arguments as it's part of a skeletal code for this project. Thanks to anyone who can help. If it helps this is what the structure looks like typedef struct LNode { int value; struct LNode *next; } LNode;

    Read the article

  • Deleting first and last element of a linked list in C

    - by LuckySlevin
    struct person { int age; char name[100]; struct person *next; }; void delfirst(struct person **p)// For deleting the beginning { struct person *tmp,*m; m = (*p); tmp = (*p)->next; free(m); return; } void delend(struct person **p)// For deleting the end { struct person *tmp,*m; tmp=*p; while(tmp->next!=NULL) { tmp=tmp->next; } m->next=tmp; free(tmp); m->next = NULL; return; } I'm looking for two seperate functions to delete the first and last elements of a linked list. Here is what i tried. What do you suggest? Especially deleting first is so problematic for me.

    Read the article

  • Sorting a Singly Linked List With Pointers

    - by Mark Simson
    I am trying to sort a singly linked list using bubble sort by manipulating ONLY the pointers, no keys. The following gets stuck in the for loop and loops infinitely. I don't understand why this is. Can anybody explain to me why the end of the list is not being found? Node* sort_list(Node* head) { Node * temp; Node * curr; for(bool didSwap = true; didSwap; ) { didSwap = false; for(curr = head; curr->next != NULL; curr = curr->next) { if(curr->key > curr->next->key) { temp = curr; curr = curr->next; curr->next = temp; didSwap = true; } cout << curr->next->key << endl; } } return head; } If I change the code so that the keys (data) are swapped, then the function works properly but for some reason I am not able make it work by manipulating only pointers.

    Read the article

  • python union of 2 nested lists with index

    - by sbas
    I want to get the union of 2 nested lists plus an index to the common values. I have two lists like A = [[1,2,3],[4,5,6],[7,8,9]] and B = [[1,2,3,4],[3,3,5,7]] but the length of each list is about 100 000. To A belongs an index vector with len(A): I = [2,3,4] What I want is to find all sublists in B where the first 3 elements are equal to a sublist in A. In this example I want to get B[0] returned ([1,2,3,4]) because its first three elements are equal to A[0]. In addition, I also want the index to A[0] in this example, that is I[0]. I tried different things, but nothing worked so far :( First I tried this: Common = [] for i in range(len(B)): if B[i][:3] in A: id = [I[x] for x,y in enumerate(A) if y == B[i][:3]][0] ctdCommon.append([int(id)] + B[i]) But that takes ages, or never finishes Then I transformed A and B into sets and took the union from both, which was very quick, but then I don't know how to get the corresponding indices Does anyone have an idea?

    Read the article

  • How to hide Lists from specific group?

    - by DanSogaard
    How to hide Lists from specific group, but at the same time allow them to add items in it?. I edited permission levels for the site and created a permission that has these privileges: List Permissions: Add Items, View Items. Site Permissions: View Pages, Open. And then assign this permission to the group along with View Only. However this would still show Lists and the users are able to access them. How can I hide it from this specific group only?.

    Read the article

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