I know this is seriously basic stuff, but I for the life of me can't seem to understand how I would go about doing this:
Q: Given the following struct definition for a Node:
struct Node
{
int value;
Node* next;
};
And given the declaration:
Node* head;
The following Linked List of Nodes has been constructed, with the head pointer assigned to the Node object 3:
head ----> 3 ----> 9 ----> 34 ----> -5 ----> NULL
Write a single C++ statement that will store the value 34 in the 3rd Node in the variable result:
int result =
Where would be a good place to start? Is this asking me to add an element to the list, or is it adding an entirely new node to the list? So confused!!
head->next->next will point to the third node in the linked list.
So,
int result = head->next->next->data;
will store the value in the third node in the list.
The question is asking you to read the third node and store it's value in result.
Linked lists employ a chain concept, where each chain-link along the entire length of the chain is connected at the front of each link.
People represent this in various ways. One example is:
struct Node {
int value;
Node* front;
};
Or:
struct Node {
int value;
Node* next;
};
When you establish the head of a linked list, you are creating the first node in the chain:
Node* head;
head = NULL; // this is an empty linked list
Whenever you want to add a node (or "link") to the chain, you pass along the new node to "Head", which keeps track of the chain:
void newNode(int value, Node* head)
{
Node *node;
node = new Node*; // or (Node*)malloc(sizeof(Node));
node->value = value;
node->next = head;
head = node;
}
Using this concept, you can add any number of links to your chain. Thomas and warun have good examples of this.
Hope this helps.
example for a loop.
Node* temp = head;
int number = 300; //the place you are looking for
if(temp)
{
int i;
for(i = 0 ; i< number && temp->next != nullptr ;i++)
{
temp = temp->next;
}
if(i == 300)
{
//found you value;
result = temp->value;
}
}
Related
I am trying to generate a node for a linked list inside a for loop. I have defined the nodes for the head, tail and a temporary node(which stores the data). But when I include it inside a for loop and print the results, it does not return anything. Any suggestions on how can I improve my code?
private:
Node *head;
Node *tail;
};
If you are creating a list of 100 nodes, then you need to allocate 100 nodes, not just one. Move new Node inside your loop, like this
void createNode(int value)
{
for (int i = 0; i<100; i++) {
node *temp = new Node;
temp->data = i;
temp->next = nullptr;
if (head == nullptr)
{
head = temp;
tail = temp;
}
else
{
tail->next = temp;
tail = temp;
}
}
Of course allocating 100 nodes in a function called createNode isn't a good idea either, but I guess you are just experimenting.
Can someone please explain me what exactly "node *create(int element)" means on the code below. I think it looks like a function but I'm not sure.
I also made some comments so you guys can have an idea of what I understand from it.Thank you for any help provided.
#include <iostream>
using namespace std;
struct node { // linear linked list
int e; //data
node *next; //pointer to itself
};
node *create(int);
int main() {
//edited I think I got it thanks for commenting any advice is welcome
node *myPtr = NULL;
myPtr = create(8);
cout << myPtr -> e;
}
node *create(int element) { //is this a function ?
//all this comments below is what I deduce so far
node *n; //declare node pointer
n = new node; //create node
n->e = element; //makes
n->next = NULL ; //makes pointer null
return n; //returns node
}
Your comments about what happens in the function are accurate.
Your use of the function is also accurate.
However, you created just a node of what could be a linked list. To create a linked list, you need more than that. You need to be able to create more than one node and link them together.
Done by hand:
node* n1 = create(8);
node* n2 = create(10);
node* n3 = create(15);
node* n4 = create(20);
node* n5 = create(30);
node* n6 = create(40);
n1->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = n5;
n5->next = n6;
Creating such linked lists by manually coding creation of every node and every link becomes tedious. Creating LinkedList as a class and having member functions in the class to perform various operations on objects of the class will be right approach.
node* create(int element) // yes, it is a function
{
node* n = new node;
n->e = element;
n->next = nullptr;
return n;
}
When you call create(), the node instance is created on the
heap with new and the pointer to that node is returned
with return n
myPtr is pointing to that node.
If you want to add more nodes then you will need to do
more work i.e. having a pointer to the first element
in the list and then appending nodes to that list.
it is helpful to create a constructor for node to initialize
the member variables instead of doing it outside
struct node
{
int e;
node* next;
node(int v) : e(v), next(nullptr)
{}
};
so instead of
n = new node;
n->e = element;
n->next = nullptr;
you can now write
n = new node(element);
I created a linked list, and made a function reverseList which takes a pointer to head and return pointer to last node.
Node* reverseList(Node *head)
{
Node* curr=head;
Node* prev=NULL;
Node* ahead;
while(curr!=NULL)
{
ahead=curr->next;
curr->next=prev;
prev=curr;
curr=ahead;
}
return prev;
}
But in main when I am doing this
int main()
{
int n;///no of elements in list
cin>>n;
Node* head=NULL;
head=createList(head,n);///creating list(it is working properly)
printList(head);
cout<<endl;
Node* temp=reverseList(head);///reversing list and storing address of list in
//new node
printList(temp);///printing reversed list properly
cout<<endl;
printList(head);///while printing this it is printing only one elements,
//which implies head pointer changes but I don't know
///how
}
My head pointer changes, and it is printing only one value. I had pass my head pointer in reverseList by value. I am providing image of output.
Comments explain fine already, trying to illustrate to make it a little clearer:
1 > 2 > 3 > 4 > NULL
^
head
Now you reverse the list, resulting in:
4 > 3 > 2 > 1 > NULL
^ ^
temp head
As you never changed head, it still points to the same node as it pointed to before the list reversal, but after reversing the list, this node is now the last one.
Side note: Forgetting to re-assign is quite a common error, so it is a good idea to encapsulate the linked list in a separate class:
class LinkedList
{
Node* _head;
public:
class Node; // just as you have already
void reverse() // now a member function
{
//reverse as you did before
// encapsulating the assignment: (!)
_head = newHead;
}
Node* head() { return _head; }
};
LinkedList l;
// ...
Node* tmp = l.head();
l.reverse();
// tmp variable points to tail...
// expecting tmp pointing to head is still an error,
// and there is no way to prevent it
// BUT the correct head can always be re-acquired:
head = l.head();
Edit in response to comment:
If you want to create a new list, you will have to copy the nodes:
Node* createReversedList(Node* head)
{
Node* cur = NULL;
while(head)
{
Node* tmp = new Node(*head);
// (provided you have an appropriate copy constructor)
tmp->next = cur;
cur = tmp;
head = head->next;
}
return cur;
}
Note the new name, reverse rather implies modifying the original list as you did.
To create a new Linked List, you need to create a new variable of Node, and perform operations on that variable.
So, the code would be something like:
Node* reverseList(Node *head)
{
Node* newRootPtr = new Node(); //Pointer to the new root. This will be returned to the calling function.
newRootPtr->next = NULL; //In the reversed list, the original head will be the last node.
Node* curr=head; //For iterations
while(curr->next!=NULL) //For every node, until the last node. Note that here, we need to stop at the last node, which will become the first node of the new List.
{
Node ahead=*(curr->next); //Create a new Node equal to the next node of the original list.
Node* aheadPtr = &ahead; //Pointer to the new node
aheadPtr->next = newRootPtr; //Point the new node to the previous node of the new list
newRootPtr = aheadPtr; //update root node
curr=curr->next;
}
return newRootPtr;
}
I have been trying to delete the first node from a single linked list. What I did is as follow
create a temporary node pointing to the head node
move the head to the next node
free the temporary node and return the head
After generating a simple linked list as : 1 - > 2 -> 3 -> 4 -> 5
and calling my method for deleting the first node the result is as not correct. It returns the following linked list: 0 -> 2 -> 3 -> 4 -> 5
I didn't get why does the 0 still exists.
#include <cstdlib>
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
Node* Delete(Node *head)
{
Node* temp = head;
head = head->next;
delete temp;
return head;
}
int main(void) {
Node* head = new Node();
Node* temp = head;
for(int i=1; i<=5; i++)
{
Node* newNode = new Node();
newNode->data = i;
newNode->next = NULL;
temp->next = newNode;
temp = newNode;
}
Delete( head = head->next );
while(head != NULL)
{
cout<<head->data<<" ";
head = head->next;
}
cout<<endl;
return 0;
}
You need to change the way you called Delete. It should be
head = Delete ( head );
The way you have your code, you assign head to be head->next and call Delete on head->next,
Furthermore the call to delete is wrong and you mix new and free to manage dynamic memory as people said you before, you have a 0 value because the initial list is 0 -> 1 - > 2 -> 3 -> 4 -> 5. You start head without any initial value and for that head->data is 0.
I want to highlight two things here-
First : The linked list your code is generating here is 0->1->2->3->4->5
Second : By looking at your code it seems that you intend to call Delete on the 2nd node (head->next) of the linked list and NOT on the first node (head).
However, the way you are calling Delete needs to be corrected first. So, If you want to delete the first node (head) of the linkedlist, call it this way:
head = Delete(head);
And you should be good to go. The output would be : 1->2->3->4->5 (which is correct based on the linked list your creates in the first place)
Hope this helps.
I think you can write your delete function in a more simpler way.
For example you can write it like this:
void Delete(nod * &p)
{
nod * t = p -> urm;
p = t;
}
I just want to point out that i am not a native english speaker so the variables might not make sense for you;
Here is the explanation:
You will reference p because it will change element will change. p = first element; nod = node; urm = next(is a pointer that memorizes the address of the first element).
Hope i helped you!
I've been working on this for about a day and haven't been able to put a series of nodes in the middle of a linked list. In all, the program I'm trying to write takes a string, another string and an integer, and places the second string at the integer location in the linked list made from the first string. I've tried quite a few strategies but they've all met with unresponsive programs and segmentation faults. My code is below:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
typedef struct node
{
int number;
char j;
struct node* next;
struct node* prev;
}node_t;
void print(node_t *head)
{
node_t *curr = head;
while(curr)
{
printf("\n%d%c\n", curr->number, curr->j);
curr = curr->next;
}
}
void insert(int index, node_t *head, node_t *tail, char* string)
{
node_t *curr = head;
node_t *newNode = (node_t*)malloc(sizeof(node_t));;
node_t *newPrev = (node_t*)malloc(sizeof(node_t));;
node_t *newNext = (node_t*)malloc(sizeof(node_t));;
int i;
while(curr->number!=index)
{
curr = curr->next;
}
//printf("\n%d%c\n", curr->number, curr->j);
newNode->prev = curr;
newNode->next = curr->next;
newNext = curr->next;
curr->next = newNode;
curr = curr->next;
for(i=0; i<strlen(string); i++)
{
curr=(node_t*)malloc(sizeof(node_t));
curr->number = i;
curr->j = string[i];
curr->prev = tail;
tail->next = curr;
tail = curr;
}
newNext->prev = curr;
}
int main()
{
node_t *curr,*head,*tail;
head=NULL;
tail=NULL;
int i;
int index = 0;
char* inputString = (char*)malloc(sizeof(char)+1);
char* inputString2 = (char*)malloc(sizeof(char)+1);
printf("Please input a string: ");
gets(inputString);
printf("%s\n", inputString);
for(i=0; i<strlen(inputString); i++)
{
curr=(node_t*)malloc(sizeof(node_t));
curr->number = i;
curr->j = inputString[i];
curr->next = NULL;
if(tail)
{
curr->prev = tail;
tail->next = curr;
}
tail=curr;
if(!head)
{
head=curr;
}
}
printf("Please input a string: ");
gets(inputString2);
printf("%s\n", inputString2);
printf("Please input a valid index: ");
scanf("%d", &index);
while(index>strlen(inputString)||index<0)
{
printf("A valid index. ");
scanf("%d", &index);
}
printf("%d\n", index);
insert(index, head, tail, inputString2);
print(head);
return 0;
}
I'd be eternally grateful if anyone could provide a way to insert the second string into the linked list as elements. I've determined that it works as far as identifying the node specified by the integer, but beyond that I'm not sure. Thanks in advance.
EDIT: Now my issue is that the program puts an rubbish node at the correct place, but then creates the nodes at the end of the list.
There are still so many problems with your code that it is probably impossible to help you in this forum without simply giving you "the answer". You might try a different website.
Some hints:
Since it is possible for head and/or tail to be modified in the insert function, you need to pass in their addresses, not just their values. I.e.,
void func(node_t **head) {
// dereference head (with *) to use it
*head = malloc(sizeof(node_t));
}
void another_func() {
node_t *head = NULL;
func(&head); // pass the address of head
}
newPrev is unused (are you compiling with a proper warning level? With gcc, add the -Wall flag).
newNext doesn't need any malloced space since it is used to point to previously-allocated space.
And there are other errors (logic errors) more difficult to describe.
My advice it to rewrite it. Declare another struct called list to hold the head and tail pointers. Write a function called make_node to create and initialize a new node given a character (and a number if you think that's necessary). Write a function called make_list that takes a string and returns a list of its characters. In the insert function, use make_list to make a list from the string to be inserted and then modify the pointers to insert it into the first list.
Storing the index numbers in the nodes is unnecessary and actually complicates things since to keep them in order you'd need to update the indices in the original list after the insertion. You can simply keep a count of how many nodes you've looped through to know the index of a node.
Adding the C language tag to your question may bring others in to help you.