I am new in Data Structure.
I came up with a question when I was trying to write code using linked list using C++.
In linked list, is pointer next, previous defined by the compiler? Or we have to name our own and it does not matter how we call it?
next and previous are not predefined. We have to define it ourself. Usually for a single linked list, we come up with a node structure which consists of a data field and anext pointer which is a pointer to a node of the same type. A simple example is as follows:
struct node{
int data; //data part
struct node *next; // next pointer - points to a node of the same type
}
Related
I created a link list and an integer field to represent the linked list.
Then I assigned the integer field to 0.
I don't know how to convert the int parameter into the linked list.
template<typename T>
struct Node{
T data;
Node* next;
};
class Integer{
private:
Node<int>* real_num;
public:
Integer(){
real_num->data = 0;
std::cout << "success!";
}
Integer(int int_convert){
real_num->data = int_convert;
}
The constructor assigns a value to a variable in a structure which has been declared but not itself constructed.
Add this to the top of your constructors.
Node<int> * real_num=new Node<int>;
Only after the Node has had memory allocated, etc is it valid to reference a variable in the struct that real_num only points to. Without 'new' real_num points to null.
You should take a look at std::list which is a container that represents a double-linked list.
If it doesn't answer your problem, so far your code is correct. You now need to add getter and setter and also utility functions to manipulate your linked list.
Edit: You have to construct your private variable before using it or will run into a undefined behavior because you gonna use a memory part that hasn't been initialized. If you are lucky enough, your program will crash and end up with a Segmentation Fault.
Take a look at the keyword new and delete to allocate/deallocate memory in C++.
I was going through the linked list and I have confusion. maybe I am mixing the concept or something else. Here is the code of creating the header node.
struct node
{
int data;
struct node *link;
};
node *head;
void main()
{
head = new node;
}
1)The first thing I want to know is how can we write struct node *link; in inside the same node structure? because using first the node structure is created then we can declare pointer of that.
2) node *head; will already declare a memory of size node, then we need to do again head = new node;?
The self referential struct can hold a pointer to itself. Please do not confuse with size of pointer to size of structure. Size of pointer is constant irrespective of data type.
struct node
{
int data;
struct node *link;
};
Had it the struct node *link be something else like struct node link, It will not compile just like you think.
regarding why allocation by using the new is required, when we do node *head, it says that head points to memory location of actual node with area for data and link.
It might be useful to read pointer concept again
A link list is a chain of objects. What you are doing here is creating a struct with two variables. One is the date to store in this node. The other is a recursive struct. This where link lists get their name. One struct links to the next. When this node is created, link has no value but you can add nodes by creating a new node and storing it in link.
As for the rest of your code, I don't think you are doing it right. Usually nodes are wrapped in a link list class so that you can control the link list by adding, deleting and searching the nodes. When you are controlling a link list you need at least two pointers. One to point to the first node in the list (also called the "head"). The second pointer is the search pointer that will start at the head and go node by node until you find what you are looking for.
Now to answer your second question when you write node* head you are only declaring the pointer. You are not declaring "a memory of size node" so in the initialize function of the link list you need to create the first node and have the head point to it head = new node;
struct Node
{
int value;
Node *next;
Node *prev;
};
This is the creation of a linked list. My question is that why do we declared the pointer of the same struct. e.g Node *next. If we are going to have a linked list of integers, can we just use int * next and int *prev instead of using Node *next.
Each element in a linked list contains not only the data (int in your case), but also a pointer to the next element (and in a doubly-linked list, like you have, a pointer to the previous element too). Without it, you couldn't construct a list longer than two elements.
A structure is use to group list of variables in one common block of memory, this helps in accessing elements using single pointer. In your question you are saying why we not use only int *next if we use that we cannot group other elements, also you cannot save value and link simultaneously.
Think of structures as containers which have objects(ints, chars..) stored inside them. To reach an object in a particular container, you need to find the container first, and hence you will need the address of the container(i.e., the address of struct).
Considering the following structure.
struct Node
{
int value;
int *next
};
You have an integer and a pointer to an integer inside struct Node. When you assign memory for the first structure, it will act like a container holding an integer and a pointer to an integer. In such a case, the chain will end with the first structure itself as you are not pointing to a second structure(from within the first structure), which can hold the pointer pointing to a third structure and so on.
If you want to link this structure to another structure of the same type(in essence creating a linked list), you will need a pointer which can point to another structure of the same type. And hence goes the need to have a pointer to a structure of same kind inside any structure which will be used for a linked list.
Now I know that why pointers are used in defining linked lists. Simply because structure cannot have a recursive definition and if there would have been no pointers, the compiler won't be able to calculate the size of the node structure.
struct list{
int data;
struct list* next; // this is fine
};
But confusion creeps up when I declare the first node of the linked list as:
struct list* head;
Why this has to be a pointer? Can't it be simply declared as
struct list head;
and the address of this used for further uses? Please clarify my doubt.
There's no definitive answer to this question. You can do it either way. The answer to this question depends on how you want to organize your linked list and how you want to represent an empty list.
You have two choices:
A list without a "dummy" head element. In this case the empty list is represented by null in head pointer
struct list* head = NULL;
So this is the answer to your question: we declare it as a pointer to be able to represent an empty list by setting head pointer to null.
A list with a "dummy" head element. In this case the first element of the list is not used to store actual user data: it simply serves as a starting "dummy" element of the list. It is declared as
struct list head = { 0 };
The above represents an empty list, since head.next is null and head object itself "does not count".
I.e. you can declare it that way, if you so desire. Just keep in mind that head is not really a list element. The actual elements begin after head.
And, as always, keep in mind that when you use non-dynamically-allocated objects, the lifetime of those objects is governed by scoping rules. If you want to override these rules and control the objects' lifetimes manually, then you have no other choice but to allocate them dynamically and, therefore, use pointers.
You can declare a list such a way
struct list head = {};
But there will be some difficulties in the realization of functions that access the list. They have to take into account that the first node is not used as other nodes of the list and data member of the first node data also is not used.
Usually the list is declared the following way
struct List
{
// some other stuff as for example constructors and member functions
struct node
{
int data;
struct node* next; // this is fine
} head;
};
and
List list = {};
Or in C++ you could write simply
struct List
{
// some other stuff as for example constructors and member functions
struct node
{
int data;
struct node* next; // this is fine
} head = nullptr;
};
List list;
Of course you could define the default constructor of the List yourself.
In this case for example to check whether the list is empty it is enough to define the following member function
struct List
{
bool empty() const { return head == nullptr; }
// some other stuff as for example constructors and member functions
struct node
{
int data;
struct node* next; // this is fine
} head;
};
In simple terms, if your head is the start node of the linked list, then it will only contain the address of the first node from where linked list will begin. This is done to avoid confusion for a general programmer. Since the head will contain only address, hence, it is declared as a pointer. But the way you want to declare is also fine, just code accordingly. Tip: If you later on want to make some changes in your linked list, like deletion or insertion operations at the beginning of the linked list, you will face problems as you will require another pointer variable. So its better to declare the first node as pointer.
The way I know how to represent a linked list is basically creating a Node class (more preferably a struct), and the creating the actual linkedList class. However, yesterday I was searching for the logic of reversing a singly linked list operation and almost 90% of the solutions I've encountered was including that the function, returning data type Node* . Thus I got confused since if you want to reverse a list no matter what operation you done, wouldn't it be in the type of linkedList again? Am I doing it the wrong way?
The linked list implementation I do all the time;
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
class linkedList
{
public:
Node* firstPtr;
Node* lastPtr;
linkedList()
{
firstPtr=lastPtr=NULL;
}
void insert(int value)
{
Node* newNode=new Node;
newNode->data=value;
if(firstPtr==NULL)
firstPtr=lastPtr=newNode;
else {
newNode->next=firstPtr;
firstPtr=newNode;
}
}
void print()
{
Node *temp=firstPtr;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
};
You approach isn't wrong, but you might be giving too much emphasis on your linkedList class.
What does that class actually contain? A pointer to the first node, and a pointer to the last node (which is redundant information, since you can find the last node by only knowing the first one). So basically linkedList is just a helper class with no extra information.
The member functions from linkedList could easily be moved inside Node or made free functions that take a Node as parameter.
Well, what is a linked list but a pointer to the first node? A list is fully accessible provided you can get to the first node, and all you need for that is a pointer to the first node.
Unless you want to store extra control information about the list (such as its length for example), there's no need for a separate data type for the list itself.
Now some implementations (such as yours) may also store a pointer to the last node in the list for efficiency, allowing you to append an item in O(1) instead of O(n). But that's an extra feature for the list, not a requirement of lists in general.
Those functions might be returning of type Node* because after reversing the linked-list they will return the pointer to the First node of the list.