linked list, where is my logic flawed? [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
so I have of course, looked through a lot of linked list help and all but i can't seem to figure out what is going wrong with mine. I think I understand the logic of other codes, but something is up with mine and I can't get it to work properly.
Code of the function:
void SparseM_list::newTerm(valueType newValue, int row, int column)
MatrixTerm *n = new MatrixTerm;
n->next = NULL;
n->column = column;
n->row = row;
n->value = newValue;
if (head != NULL)
{
cur = head;
while (cur->next != NULL)
{
cur = cur->next;
cout << "does it ever get inside the while loop? cur and curnext -> " << cur << " " << cur->next << endl; <-- never outputs
}
cur->next = n;
}
else //if head is null, n will be the starting point
{
head = n;
}
delete n;
}
and below is the private struct/variables of my sparse matrix using linked list
struct MatrixTerm {
valueType value; //store value of matrix element
int column; //store column position
int row; //store row position
MatrixTerm *next; //point to next node in the linked list
};
MatrixTerm *head; //head point for the linked list
MatrixTerm *cur, *prev;
So basically my logic is this
New term information is dynamically allocated to Matrix Term n.
If the head is null (which is set by the default constructor), then head = n
2nd set of data goes in. head != Null, so I set cur pointer equal to the head
the while loop is skipped for the 2nd data, because head->next should be null and so cur->next should be null. I set the cur->next equal to n
3rd data goes in. Cur->next has n from the previous, so it enters the while loop. Current is set to be cur->next. It checks the while loop condition, and this time, cur->next should be null, so it goes to setting cur->next = n (3rd data set).
However, it never enters the while loop. Where am I messing things up? the while loop is used to traverse through the linked list.

This statement
delete n;
does not make sense. Remove it.
I hope that initially the data member head indeed is set to NULL (or nullptr).
An alternative implementation of the function can look like
void SparseM_list::newTerm(valueType newValue, int row, int column)
{
MatrixTerm *n = new MatrixTerm { newValue, column, row, nullptr };
MatrixTerm **current = &head;
while ( *current ) current = &( *current )->next;
*current = n;
}
If the list allows to append new nodes it would be helpful to declare also one more data member tail. In this case a new node will be added to the tail that is more efficient then each time to execute the loop.
Also think about to remove data members cur and prev and use them as local variables of the methods.

You should not delete n;, because it will release the memory of your list nodes. You see, you keep push your key into a lock but before open the door you pull out the key...Can you come into the house?
ps, delete the nodes should be held in the desturctor of the list object.

Related

Append last n nodes of a singly LL to the start [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 months ago.
Improve this question
Please help me find the error in the given code, After returning the new head and using the printing function, no output gets displayed
Node *interChange(Node *head, int n){
Node *tempoo = head;
Node *temp = head;
int tot =0;
while(tempoo != NULL){
tempoo = tempoo->next;
tot++;
}
int count =0;
while(count < tot-n){
temp=temp->next;
count++;
}
Node *newHead = temp->next;
temp->next=NULL;
Node *newTemp = newHead;
while(newTemp != NULL){
newTemp = newTemp->next;
}
newTemp->next = head;
return newHead;
}
The last statement before the return performs an invalid dereferencing: newTemp->next = head; when at that point it is guaranteed that newTemp is NULL. This leads to undefined behaviour.
Your function returns the new head, so make sure the caller (which you didn't include) will use that new head pointer when printing the list.
Some other remarks:
The code does not deal well when the list is empty
The code does not deal well when n is greater than the number of nodes in the list, or is negative. It would maybe be a good idea to use modulo arithmetic to bring that value in range.
The cutoff point is wrongly calculated. For n is 0, the original head node will still become the new tail (if all the rest is corrected).
In C++ you should be using nullptr instead of NULL
Calling all your variables something like temp is not helpful. You can do with fewer variables, and use more telling names.
Here is a correction to your function:
Node *interChange(Node *head, int n) {
if (head == nullptr) return nullptr; // Boundary case
Node *tail = head;
int tot = 1; // We already have the head
// Check whether there is a next node, so we end up with the tail
while (tail->next != nullptr) {
tail = tail->next;
tot++;
}
// Make list circular
tail->next = head;
// Bring the n argument within a valid range
n %= tot;
// Find new tail
for (int count = tot - n; count; count--) {
tail = tail->next; // Reuse tail variable to identify new tail
}
// Reuse variable to identify new head
head = tail->next;
// Make list non-circular again
tail->next = nullptr;
return head;
}
The caller should capture the returned pointer. For instance:
Node *head;
// Initialise head with a list ...
// (your code here)
// And then:
head = interChange(head, 3);

Improve my solution to basic C linked list management functions

I would appreciate some help relative to my code solution, which deals with linked list management in C. I'll already declare the only strange thing with my request: I am writing a C++ file, but I am actually mostly leveraging C resources (malloc(), free(), etc.); that said, given the basic code I provide, I am confident no one will have trouble with that.
I want to write a function to add elements to the end of the list and one to delete elements from it, that work in any edge case. Given my desire, the removal function was the one that I struggled the most with, but also the one that made me realize how little I am understanding pointers.
I will now share the code I produced, that should be working fine, but:
It can surely be greatly improved both in terms of clarity and performance
I think that showing it to the community will highlight many of the flaws present in my solution
// The plan is to create a linked list and to be able to add and delete its elements
#include <iostream>
using namespace std; // I can write output lines as cout << "Hi!", rather than std::cout < "Hi!"
#include <cstdlib> // needed for malloc() in C++
struct node {
int data;
node* nextPtr; //"struct node* nextPtr;" : This would be the syntax for plain old C: you always have to type the "struct" keyword
};
node* createElement(int data) {
node* newElemPtr = (node*)malloc(sizeof(node)); // the "(node*)" cast is required by C++, and is not used in C
newElemPtr->data = data;
newElemPtr->nextPtr = NULL;
return newElemPtr;
}
void appendElement(int data, node** head) { // Adds a new node at the end of the list
// I pass as argument a pointer to pointer (double pointer) to node, so that I can edit the head node
// if the list is empty, without having to return a new node pointer as head: my function indeed features
// "void" in its signature
node* elemPtr = NULL;
elemPtr = createElement(data); // elemPtr is a pointer to the new node
if (*head == NULL) {
*head = elemPtr;
}
else {
node* currPtr = *head; // currPtr is the temporary variable that visits each node of the linked list
while (currPtr->nextPtr != NULL)
currPtr = currPtr->nextPtr;
currPtr->nextPtr = elemPtr; // Set last element's nextPtr to "elem", i.e., a pointer to the new element
}
};
void removeElement(int data, node** head) { // Remove all the nodes whose data content matches the "data" argument
int presence_flag = 0; // Flag used to check whether the required data is present at all in the linked list
if (*head == NULL) {
return;
}
else {
node* currPtr = *head;
node* prevPtr = *head;
while (currPtr != NULL) {
// This is the case in which I find a node to delete (it matches the "data" query), and it is not the first of the list
if (data == currPtr->data && currPtr != *head) {
prevPtr->nextPtr = currPtr->nextPtr; // Link the node ahead of the one to delete with the one behind
free(currPtr);
currPtr = prevPtr; // In the next loop, I will resume the analysis from the previous node, which now points to an unvisited one
presence_flag = 1;
}
// This is the case in which I find a node to delete and it is the first of the list
else if (data == currPtr->data && currPtr == *head) {
// This is the case in which I have to delete the first node, but the list features other nodes
if (currPtr->nextPtr != NULL){
*head = currPtr->nextPtr; // Move *head forward
currPtr = *head; // Do the same with currPtr, in order not to break the while() loop
free(prevPtr); // As *head has already been re-assigned, I leverage prevPtr to delete the old *head
presence_flag = 1;
}
// This is the case in which I have to delete the first and only node of the list
else {
*head = NULL;
currPtr = *head;
presence_flag = 1;
}
}
// This is the case in which the current node does not match the queried "data" value
else{
prevPtr = currPtr; // Update prevPtr
currPtr = currPtr->nextPtr; // Move currPtr forward
}
}
}
if (presence_flag == 0)
cout << "There is not any node with value " << data << " in the linked list.\n\n";
// Q1: Am I causing any memory leak by using *head == NULL instead of free(*head)?
// Q2: Should I free() everythin before ending the main(), at least as a good practice?
// Q3: Is there a way to make this function by not using a double pointer as input and by also keeping "void" as return value?
// Of course, it should still work in the tricky edge case of the last element in the list that has to be deleted
};
void printLinkedList(node* head) { // Here I return nothing, so I can freely edit "head" (i.e., there is no need for a temporary pointer)
if (head == NULL) {
cout << "The linked list is empty.\n";
}
else {
int elemCounter = 0;
while (head != NULL) {
elemCounter += 1;
cout << "elem N. " << elemCounter << ": data value = " << head->data << "\n"; // head->data is equal to (*head).data
head = head->nextPtr;
}
}
};
int main(int argc, char* argv[])
{
//cout << "Size of a single node of the list = " << sizeof(node) << "\n";
// == 16. On a 64 bits machine, an int ("data") requires 4 bytes.
// The pointer requires 8 bytes; the remaining 4 bytes are padding
node* head = NULL;
appendElement(1, &head);
appendElement(2, &head);
appendElement(3, &head);
printLinkedList(head);
cout << "\nRemoving element with data value = 1...\n\n";
removeElement(1, &head);
printLinkedList(head);
cout << "\nRemoving element with data value = 2...\n\n";
removeElement(2, &head);
printLinkedList(head);
cout << "\nRemoving element with data value = 3...\n\n";
removeElement(3, &head);
printLinkedList(head);
cout << "\nRemoving element with data value = 4...\n\n";
removeElement(4, &head);
printLinkedList(head);
cout << "\nRemoving element with data value = 1...\n\n";
removeElement(1, &head);
printLinkedList(head);
cout << "\nRemoving element with data value = 2...\n\n";
removeElement(2, &head);
printLinkedList(head);
return 0;
}
As you can see from the comments embedded in the code, I have 3 doubts that captured my interest while coding the node removal function:
Q1: Am I causing any memory leak by using *head == NULL instead of free(*head)?
Q2: Should I free() everything before ending the main(), at least as a good practice?
Q3: Is there a way to make this function by not using a double pointer as input and by also keeping "void" as return value? Of course, it should still work in the tricky edge case of the last element in the list that has to be deleted
I hope that featuring these "additional" questions is something reasonable to put here, as maybe someone in the future may have the same doubts I had.
I know there are plenty of ready-to-copy-and-paste solutions for my task, but I think I can really learn this stuff if I see why my precise design choices are not optimal/wrong.
I thank everyone for the time spent reading this.
There are many duplicated code. Also the function should not output any message. It is the caller of the function that decides whether to output a message. So the function should have the return type bool if you are considering the program as a C++ program or bool or int if you are considering the program as a C program.
The function removeElement invokes undefined behavior because in its paths of execution you are not always resetting correctly values of the pointers currPtr and prevPtr after deleting a node.
For example after this code snippet
if (data == currPtr->data && currPtr != *head) {
prevPtr->nextPtr = currPtr->nextPtr; // Link the node ahead of the one to delete with the one behind
free(currPtr);
currPtr = prevPtr; // In the next loop, I will resume the analysis from the previous node, which now points to an unvisited one
presence_flag = 1;
}
prevPtr and currPtr will be equal each other.
I would define the function the following way
int removeElement( node **head, int data )
{
int deleted = 0;
while ( *head )
{
if ( ( *head )->data == data )
{
deleted = 1;
node *current = *head;
*head = ( *head )->next;
free( current );
}
else
{
head = &( *head )->next;
}
}
return deleted;
}
As for your question
Q3: Is there a way to make this function by not using a double pointer
as input and by also keeping "void" as return value? Of course, it
should still work in the tricky edge case of the last element in the
list that has to be deleted
then in C you can not achieve this. In C++ you can pass the pointer to the first node by reference. In C passing by reference means passing an object indirectly through a pointer to it. So in C you have to use a double pointer in such a case.
Of course just setting a pointer to NULL without freeing data pointed to by the pointer that was dynamically allocated produces a memory leak. And you should free all the allocated memory then it is not required any more.

Seg Fault: Linked List Node Insertion Function [C++]

I have created a function called 'Insert' for inserting a new node in a Linked List. It takes the value and the head node for insertion.
When I manually add the nodes myself, the program runs as expected however
I get a segmentation fault when I use the function for adding a node.
I am able to make the function work with a couple of little tweaks but there's another catch, I lose the head node's property of just being a pointer, it now contains some garbage data in it which gets printed when I print the LinkedList.
The tweak I perform is:
Change Line 26 to: A->next = NULL;
Change Line 17 to: while(temp->next != NULL)
The 'segmentation fault' occurs at Line 20 (when the tweak is not done):
Line 20 -----> temp->next = addTo;
I've already tried passing the arguments by reference, using global variables for the head node and checking the logic of the function.
The logic works for manually adding a node.
I have attached the complete code below:
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int data;
ListNode *next;
};
void Insert(int x , ListNode* head)
{
ListNode* addTo = new ListNode();
addTo->data = x;
addTo->next = NULL;
ListNode* temp;
temp = head;
while(temp != NULL)
temp = temp->next;
temp->next = addTo;
}
int main()
{
ListNode* A;
A = NULL;
//Inserting A Node Manually
// ListNode* first = new ListNode();
// first->data = 9;
// first->next = NULL;
// while(A != NULL)
// A = A->next;
// A = first;
//Inserting using Insert function.
Insert(2,A);Insert(3,A);Insert(6,A);Insert(7,A);
//Printing
ListNode* temp = A;
while(temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
return 0;
}
I expected the node to be added to the list as the logic seems to be correct, however I am getting a segmentation fault.
Any help/insight into this would help a lot.
Thank You.
Problem 1:
while(temp != NULL)
temp = temp->next;
temp->next = addTo;
Guarantees that temp will be NULL when while(temp != NULL) exits. that means there is no temp to get the next from.
Rather than solve this here, I'm going to move on to problem 2 and kill two birds with one stone.
Problem 2:
void Insert(int x , ListNode* head)
leaves you with no way to update the caller if head is changed in the Insert function. You can change the object pointed at by head, but head itself is just a copy of an address. If you change this copy to point at another address, the caller does not know.
This means every time you call Insert(<number>, A);, A will always be NULL.
Solution:
Pass head into Insert by reference so that it can be updated.
void Insert(int x , ListNode*& head)
^ reference to pointer
head's job is to point at the first item in the list. This makes means it does the same thing as any next pointer: It points at the next item. The only difference is the name. We can get rid of this difference by adding an extra indirection, a pointer to head.
ListNode ** temp = &head;
Note that we cannot use a reference (ListNode *& temp) here because once you initialize a reference to refer to an object, it cannot be changed to refer to a different object. A pointer you can change, allowing us to iterate through the list and always point temp at the next next.
Now head or any next is simply temp. This makes head exactly the same as every other next variable and no special cases are required.
void Insert(int x , ListNode*& head)
{
ListNode* addTo = new ListNode();
addTo->data = x;
addTo->next = NULL; // consider making a smarter ListNode constructor that makes
// it impossible to forget to set next.
ListNode ** temp = &head; // we can now manipulate the address in head through temp
while(*temp != NULL) // note the dereference to get the pointed at pointer
// temp won't be null, but it could be pointing at a pointer
// that is null, and that is the end of the list
{ // I always use the optional braces. They prevent confusion.
temp = &(*temp)->next; //get pointer to the next next pointer
// we can now manipulate it exactly the same as head.
}
// we exit the loop with a pointer to the next pointer that we wish to point at
// the new list item regardless of whether it's head or the next of some later
// link in the list
*temp = addTo; // update the pointed at pointer with the new Node.
}
The Community Addition the first answer of How do I properly delete nodes of linked list in C++ demonstrates how to use the same pointer-to-pointer trick to make removing nodes easy.

Printing nodes from REAR to FRONT enters infinite loop

I am trying to output the elements from each node starting from right (rear/tail) to left (head/front). However, my program enters an infinite loop that displays the same element over and over again. Despite its infinite loop, the function that I created DisplayFromLeftToRight() (found below the DisplayFromRightToLeft() function) works like a charm, but this doesnt...
void DisplayFromRightToLeft()
{
node *newnode = rear;
int num = 1;
while (newnode != NULL)
{
cout << "Node # " << num << ": " << newnode->data << endl;
newnode = newnode->previous;
num++;
}
return;
}
This is the working code for printing element from each node from LEFT to RIGHT..
void DisplayFromLeftToRight()
{
node *newnode = front;
int num = 1;
while (newnode != NULL)
{
cout << "Node # " << num << ": " << newnode->data << endl;
newnode = newnode->next;
num++;
}
return;
}
If you believe that my DisplayFromRightToLeft() function is correct, I assume that the problem is from the INSERT function, take a look:
void INSERT(int _data)
{
node *newnode = new node;
newnode->data = _data;
newnode->next = NULL;
newnode->previous = newnode;
rear = newnode;
node *index = new node;
index = front;
if (isEmpty())
front = newnode;
else
{
while (index->next != NULL)
{
index = index->next;
}
index->next = newnode;
}
}
Looks like INSERT always sets previous to a valid address, so your while (newnode != NULL) loop will never end, because it sets newnode = newnode->previous each time.
You are correct that the problem seems to be in your INSERT function, and/or any other code that determines what is in your list.
Your Display...() functions look OK as far as not looping, by themselves, but by making them rely on a while(someNode != NULL) loop, they are dependent on the assumption that the list data is well-formed. Specifically, the first node must have a previous pointer to NULL, and the last node must have a next pointer to NULL, or else one of those Display functions will loop until it finds a NULL.
Looking at the INSERT function, if you follow the steps, you will see that it assigns a new valid address to newnode, and then sets previous to that valid address, while next gets NULL, and it can assign next to something else. How would previous ever be NULL? Previous also points to the inserted node itself, which looks like any loop following previous is just going to keep looking at the same node.
Whenever working with linked lists that I implement, I always step through the code and diagram what is going on - on paper is best, rather than just imagination. Only draw things you actually have your code do. Otherwise, you are probably assuming the resulting list data is what you intended, and not what you've actually coded.
You should change:
newnode->previous = newnode;
To:
newnode->previous = rear;
Line:
newnode->previous = newnode;
has no sense. It is like saying that I am my own father.

Reverse Traversing singly linked list in C++

Recently I have been asked this question on an interview. All I could do is traverse from 9 to 1 from a linked list starting from 0 to 9. Here is the code:
#include <iostream>
typedef struct node {
int data; // will store information
node *next; // the reference to the next node
};
node *head;
int printList(node *traverse) {
if (traverse->next == NULL) {
return -1;
}
traverse=traverse->next;
printList(traverse);
cout << traverse->data << endl;
return 0;
}
int main() {
node *temp = NULL;
node *begin = NULL;
for (int i = 0; i < 10; i++) {
temp = new node;
temp->data = i;
if (begin == NULL) {
begin = temp;
}
if (head != NULL) {
head->next = temp;
}
head = temp;
head->next = NULL;
}
head = begin;
printList(head);
return 0;
}
1) How can I print 0(the first element) with the printList() recursive function?
2) How can I replace printList() recursive function with while loop?
3) If asked in an interview, does the main() function has proper node initialisation and insertation?
They are four possible ways to achieve this, each of which having its own merits.
Recursion
void print_list(node* traverse)
{
if (traverse == NULL) return;
print_list(traverse->next);
std::cout << traverse->data << std::endl;
}
This is maybe the first answer to come in mind. However, the process stack size is limited, so recursion has a pretty low limit. A big list will provoke a stack overflow. This is not a very good design in C++.
Iteration
void print_list(node *n)
{
using namespace std;
deque<node*> res;
for(;n != NULL; n = n->next) res.push_back(n);
for_each(res.rbegin(), res.rend(), [](node* n){cout << n->data << endl;});
}
Of course, if you want to make it the iterative way, you will need to stack the node pointers yourself (on the process heap) and not delegate this job to the call stack. This method lets you print far bigger lists, and is O(n) in computations. It is, however O(n) in memory usage, but you already have a list which use O(n) memory. So this should not be an issue. However, you may really need to avoid memory consumption. Which brings us to the next idea.
Double iteration
void print_list(node *head)
{
node* last = NULL;
while(last != head)
{
node* current = head;
while(current->next != last)
current = current->next;
std::cout << current->data << std::endl;
last = current;
}
}
This may seem a dumb solution, as it has O(n^2) complexity, but that is computation-complexity. It has O(1) memory complexity and, depending on the actual context and exact problem, it may be the answer you need. But this O(n^2) complexity is a lot to pay. Especially if n is so big you wanted to avoid another O(n) allocation. Which brings us to the last idea.
Hack the container
void print_list(node *head)
{
node* last = NULL;
for(node* next; head != NULL; head = next)
{
next = head->next;
head->next = last;
last = head;
}
for(node* next; last != NULL; last = next)
{
next = last->next;
last->next = head;
head = last;
cout << last->data << endl;
}
}
You first modify the container, then iterate in your new order. On a single-linked list, you can just reverse the links, then reverse-iterate while reversing the links again. The beauty of it is it stays O(n) in computing, and O(1) in memory. The problem is that you invalidate the full container while doing this : your outputing operation does not leave the list constant : this is not exception-safe: if your operation fails in middle of iteration, the list is not valid anymore. This may or may not be an issue depending on the problem.
There's an old trick for traversing the list in reverse with a while loop.
You walk the loop in the forward direction, but as you leave each node, you reverse the link -- i.e., you get its current value (the pointer to the next node), but then set it so it contains a pointer to the previous node. When you reach the end of the list, you now have a singly-linked list that goes the opposite direction -- i.e., following the pointers will take you back to the beginning of the list.
So then you walk back to the beginning, printing each node's value out as you go, and (again) reversing the links so when you're done, the list is as it started, with links going from beginning to end.
Note, however, that this can lead to problems in (for one obvious example) multi-threaded code. The entire traversal of the list from beginning to end and back to the beginning has to be treated as a single, atomic operation -- if two threads try to traverse the list simultaneously, very bad things will happen. Likewise, making this exception-safe can be somewhat challenging as well.
IOW, these are rarely effective solutions to real problems (but the same is generally true of linked lists in general). They are, however, effective ways of showing an interviewer that you can play stupid linked-list tricks.
If your list is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
1) You want to output the list reversed, your printList should look like this:
int printList(node* traverse)
{
if (!traverse)
return (-1);
printList(traverse->next);
std::cout << traverse->data << std::endl;
return (0);
}
2) It is not really possible with a while loop, unless you do really ugly things like concatenating every node's data to the beginning of the result string that you will print.
3) Your main seems very strange to me. I don't understand why your 'head' variable is global, why not in the main itself?
Last but not least, why don't using std::list?
I was asked a question containing this in the interview. It was intended to traverse the single list from both ends simultaneously. So reversing the single list was not an option. Also, memory space complexity should be O(1). I try to solve with nested loops with O(n^2) time complexity. However, more effective way is to use XOR linked list which was mentioned by #chuckcottrill and #jerry-coffin. Single list can be converted to XOR linked list by applying xor operation to prev and next pointers of node. XOR linked list based on the following property of XOR operation.
a^a^b = b (order of left side is not important)
Let's consider a node in single list and its neighboring nodes:
X: address of prev node , Y: address of next node
While converting to XOR list Y' = X^Y (Y': new value of Y)
While reverse traversing on XOR list Y^(Y') =Y^Y^X=X
So we can attain prev node (X) and do reverse traversal. The following code converts the single list to XOR linked list and does reverse traversal (forward traversal is also possible at the same time):
node* curr = head;
node* prev = NULL;
node* next= curr->next;
while (curr) {
next = curr->next;
// apply xor to prev and next
curr->next = (node*)((uintptr_t)(prev)^(uintptr_t)(next));
// move pointers forward
prev = curr;
curr = next;
}
// prev becomes tail node
// -- Reverse Traversal --
curr = prev ; // curr points to tail
prev = NULL;
node* temp;
while (curr) {
cout << curr->data << " ";
temp = curr;
// apply xor to prev and next
curr = (node*)((uintptr_t)(prev)^(uintptr_t)(curr->next));
prev = temp;
}
Please correct me if I am wrong.
This solution uses an Iterative approach. An extra "previous" pointer is used to maintain the node that will eventually follow the node in the reverse order of the list.
public static Nodes reverse(Nodes head){
Nodes temp;
Nodes previous=null;
while(head!=null)
{
temp=head.next;
head.next=previous;
previous=head;
head=temp;
}
return previous;
}
1) Change
if (traverse->next == NULL)
to
if (traverse == NULL)
2)
while(traverse != NULL) {
// print sth
traverse = traverse->next;
}
3) seems ok to me. Why do you declare head outside of main?
traverse->next = traverse;
A possible solution you could use. Another possibility,
traverse = (traverse->next)- (traverse);
but you must error check for over/underflow.