EDIT: Figured out the problem. Also if you found this through google or another search engine here is where I went wrong and how to fix it.
My deleteNode() method was moving through the list properly with the correct temp and keeping the head untouched. Where I was going wrong was in what I was returning as the result of the method. I was returning either temp or newNode which is incorrect because it goes through the list until it finds defined position. Once it finds that defined position it it would reassign the ->next pointer to point to the next->next> pointer which is correct but again I was returning the wrong thing. Because we had moved through the list using temp/NewNode we lost the header and we were returning the position we found and whatever was still in the next positions of the list.
How we fix this is returning the head (which is what is passed into the method). The reason why this works is because we have to understand how LinkedLists work. The pointers of each node point to the next node. Ex. we have a linked list |A|| - |B|| - |C|| - |D|| - |E|| - |F||
If we want to delete Node C we move to node B using the temp pointer and then assign the B->next to temp->next->next Thus skipping over C node and assigning D node.
NOTE: (From what I know this does not actually free the memory of C node so it isn't best practice because you can cause memory leaks this way) You should use the free() method on the C node.
Here is the code I ended up using
struct node* DeleteNode(struct node* head, int pos) {
struct node* temp = head;
int length = LinkedListLength(temp);
int i;
if(pos <= 0 || pos > length){
printf("ERROR: Node does not exist!\n");
}else{
if(pos == 1){
head = head->next; //move from head (1st node) to second node
}else{
for(i = 1; i < pos-1; ++i){ //move through list
temp = temp->next;
}
temp->next = temp->next->next;
}
}
return head;
}
Hopefully that helps understand how I went out fixing it.
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
ORIGINAL POST
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
EDIT: Note: This is a homework assignment I have spent a few days (estimated 4 hours) programming it I am just stuck on this one part. You can view my attempt below
I've been able to insert and delete from begining/end however I can't seem to get my delete node at position N in linkedlist to work.
My psuedocode looks like this:
LinkedList: 1,3,5,7,9,23
Grab LinkedList
Create new struct node A = head
Move through linkedlist until
position
Assign node to node->next
return linkedlist
EXAMPLE INPUT
Node structure
int data;
struct node* next;
int values[] = {1,3,5,7,9,23};
struct node* llist = CreateList(values,6);
llist = DeleteNode(llist, 1);
llist = DeleteNode(llist, 5);
llist = DeleteNode(llist, 3);
Which should leave the llist with the values 3, 5, 9 once the code has been run However, It is replacing the first node with a 0
Actual Code:
struct node* DeleteNode(struct node* head, int pos) {
struct node* temp = head;
struct node* newNode = head;
int length;
int i;
printf("DeleteNode: position = %d \nBefore: ", pos);
PrintList(temp);
if(pos <= 0){ //node does NOT exist
printf("ERROR: Node does not exist!\n");
}else{ //node DOES exist
length = LinkedListLength(temp);
if(length < pos){ //if length < position Node does not exist
printf("ERROR: Node does not exist!\n");
}else{
if(pos == 0){
newNode = temp->next;
}else if(pos == 1){
newNode = temp->next;
}else{
for(i = 1; i < pos; i++){
printf("i = %d\n", i);
temp = temp->next;
newNode->next;
}
if(temp->next == NULL){
newNode = NULL;
}else{
newNode = temp->next;
}
}
printf("After: ");
PrintList(newNode);
printf("\n");
}
}
return newNode;
}
EDIT #2: Code typo
Thanks for any help in advance. From what I have concluded my problem is that I am not moving through the list properly but I am unsure as to why I am not.
In your code, you have the line
newNode->next;
in your for loop. That operation doesn't do anything.
You also have
newNode-> = NULL;
which is not valid C, and I have no idea how you got that to compile.
But really, don't use that loop. A linked list is one of the most basic recursive data structures. As a result, almost all algorithms manipulating them are most elegant as a recursive solution.
typedef struct node node_t;
node_t* delete_at_index(node_t* head, unsigned i)
{
node_t* next;
if(head == NULL)
return head;
next = head->next;
return i == 0
? (free(head), next) /* If i == 0, the first element needs to die. Do it. */
: (head->next = delete_at_index(next, i - 1), head); /* If it isn't the first element, we recursively check the rest. */
}
Removing a given node n from a singly-linked list can be boiled down to this operation:
Set the pointer that points to n to point instead to n->next.
You can break this down into two operations:
Find the pointer that points to n;
Set that pointer to n->next.
The complication arises because the pointer that points to n might either be the p->next field of the previous node in the list, or the head pointer (if n is the first node in the list).
Your code does not appear to be complete - it doesn't ever set the ->next field of any node to anything, so it's hard to say what's actually wrong.
// Remove list's node located at specified position.
// Arguments:
// head -- list's head
// pos -- index of a node to be removed (1-based!!!)
struct node* DeleteNode(struct node* head, int pos)
{
struct node* node;
struct node* prev;
int length;
int i;
printf("DeleteNode: position = %d \nBefore: ", pos);
PrintList(head);
// Check position's lower bound. Should be >= 1
if(pos <= 0) { //node does NOT exist
printf("ERROR: Node does not exist!\n");
return head;
}
// Seek to the specified node, and keep track of previous node.
// We need previous node to remove specified node from the list.
for(i=1, prev = 0, node = head; i < pos && node != 0; i++) {
prev = node;
node = node->next;
}
// Out of range
if(0 == node) {
printf("ERROR: Index out of bounds!\n");
return head;
}
// #node points to a list's node located at index pos
// #prev points to a previous node.
// Remove current node from the list.
if(0 == prev) {
head = node->next;
}
else {
prev->next = node->next;
}
free(node);
return head;
}
Your DeleteNode doesn't delete a node, it removes pos nodes from the front of the list. So you're trying to remove 9 items from a list that only contains 6, resulting of course in an empty list (NULL). Also, your code is overly complex and contains remnants of previous attempts. Please don't do that to yourself or to us; provide simple clean code and it will be easier to understand and to fix.
Figured out your for loop isn't reaching the desired position you wanted.
Better use equal to sign for the constraint it will work.
e.g.
for (i=1;i<=position-1;i++)
{
}
Related
I am trying to print the values stored in a linked list but i'm running into a infinite loop.Please could some one tell me what is wrong with my code. I am able to successfully collect the data of the nodes but when printing the list i run into a continuous loop. Any help would be greatly appreciated. Thanks in advance
#include <stdio.h>
#include <stdlib.h>
struct node {
int data; //4 bytes
struct node *next; // 4bytes 32 bit and 8 bytes i 64bit cp
};
int main(){
struct node *head,*newnode,*temp;
head = NULL ;
temp = head;
int count=0, choice=1;
while(choice){
newnode = (struct node *)malloc(sizeof(struct node));
printf("Enter data:");
scanf("%d",&newnode-> data);
newnode->next = head;
if(head == 0){
head = temp = newnode;
}
else{
temp->next = newnode;
temp = newnode;
}
printf(" %d ",temp->data);
printf("Do you want to continue? 0/1");
scanf("%d",&choice);
}
int i = 0;
temp = head;
while( temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
}
I doubt it's within the scope of the homework problem in question, but it's really helpful to break linked list tasks down into smaller problems.
We start with this node definition:
struct node {
int data; //4 bytes
struct node *next; // 4bytes 32 bit and 8 bytes i 64bit cp
};
Which I'm going to typedef to make my life slightly easier.
typedef struct node {
int data; //4 bytes
struct node *next; // 4bytes 32 bit and 8 bytes i 64bit cp
} node_t;
Let's find the last node for a given head. We'll create a node_t pointer called current and use it to walk the list until it's at the last node. We'll know it's the last because its next member will be NULL. Of course, if head is NULL, then we'll just return NULL immediately.
node_t *last_node(node_t *head) {
if (head == NULL) {
return NULL;
}
node_t *current;
for (current = head; current->next != NULL; current = current->next);
return current;
}
Now, let's add a value to a list with a given head. We can provide a shortcut by returning a pointer the new last node. We'll also short-circuit a lot of work if head is NULL.
Otherwise we'll get the last node using the last_node function we defined, set its next to the new node, and return a pointer to the new node.
node_t *add_to_list(node_t *head, int value) {
node_t * new_node = malloc(sizeof(node_t));
new_node->data = value;
new_node->next = NULL;
if (head == NULL) {
return new_node;
}
node_t *last = last_node(head);
last->next = new_node;
return new_node;
}
And finally we can write a function to print the list. Given that you've already seen walking the list, this should look pretty familiar.
void print_list(node_t *head) {
for (node_t *current = head;
current->next != NULL;
current = current->next) {
printf("%d ", current->data);
}
}
Breaking down big problems into smaller problems is crucial. Practice it!
When you create a new node, you set it's "next" node to the head node. That's how the loop is made.
Set it to NULL.
And afterwards you set the new node as the "current node's next node" and the "current node" as well.
I believe you wanted to set it to temp's next node and then move the temp onto it's next node.
Also please don't compare head with 0... If you expect it to be NULL compare to NULL.
In our class right now we're covering nodes and linked lists, and are working on our first linked list program.
We've been given the following guidelines by the teacher:
Make sure your main function will accept 10 characters from STDIN and create a linked list with those characters (so your nodes will have a char member). Then, add an additional function called reverse. The purpose of the reverse function will be to create a copy of the linked list with the nodes reversed. Finally, print off the original linked list as well as the reversed linked list.
I've gotten it all written out, and I've compiled it with no errors - but the program doesn't work as intended, and I'm not entirely sure why. I'm sure it has something to do with how I've set up the pointers to "walk" the nodes - as the debug I put in shows it looping twice per user input letter. Specifications are that we're only supposed to use one function, and we pass a Node* to the function, and it returns the same. The function cannot print out anything - only make the second list that is a reverse of the first.
Any help would be greatly appreciated, I'm not terribly good at this yet and I'm sure I've made some rather silly mistakes.
#include <stdio.h>
#include <stdlib.h>
//struct declaration with self-reference to make a linked list
struct charNode {
char data;
struct charNode *nextPtr;
struct prevNode *prevPtr;
};
typedef struct charNode Node; //makes Node an alias for charNode
typedef Node *NodePtr; //makes NodePtr an alias for a pointer to Node (I think?)
//function declaration for a reverse function
Node* reverse(Node *stPtr);
int main(void)
{
//main function takes 10 letters and puts them in a linked list
//after that, it calls the reverse function to create a reversed list of those characters
//lastly it prints both lists
NodePtr newNode = NULL;
char input;
Node* revStart;
unsigned int counter = 0;
printf("Enter 10 letters to make a list: ");
NodePtr currentPtr = NULL; //sets currentPointer to startNode.
NodePtr previousPtr = NULL; //set previousPointer to null to start
while(counter<= 10)
{
scanf("%c", &input); //gather next letter
NodePtr newNode = malloc(sizeof(Node)); //creates a new node
if (newNode != NULL) //checks to make sure the node was allocated correctly
{
newNode->data = input; //makes the new node's data == input
newNode->nextPtr = NULL; //makes the nextPtr of the newNode NULL
}
currentPtr = newNode; //sets currentPtr to the address of the newNode
if(previousPtr == NULL) { //first time around previousPtr == NULL
newNode->nextPtr = newNode;
previousPtr = newNode; //sets previousPtr to the address of the new node (1st time only)
} else { //afterwards, currentPtr won't be NULL
previousPtr->nextPtr = currentPtr; //last node's pointer points to the current node
previousPtr = newNode; //update previous pointer to the current node
}
++counter;
//debug
printf("\nLoop #%d\n", counter);
}
revStart = reverse(newNode);
puts("The list is: ");
while (newNode != NULL){
printf("%c --> ", newNode->data);
currentPtr = currentPtr->nextPtr;
}
puts("NULL\n");
}
//reversing the nodes
Node* reverse(Node *stPtr)
{
//make a new node
NodePtr currentPtr = stPtr->nextPtr; //get the next letter ready (this will point to #2)
NodePtr prevRevPtr = NULL; //previous reverse node pointer
Node* revStart;
for(unsigned int counter = 1; counter <= 10; ++counter)
{
NodePtr revNode = malloc(sizeof(Node));
if(revNode != NULL) //if reverseNode is allocated...
{
if(prevRevPtr = NULL) //if previousReversePointer = NULL it's the "first" letter
{
revNode->data = stPtr->data; //letter = current letter
revNode->nextPtr = NULL; //this is the "last" letter, so NULL terminate
prevRevPtr = revNode; //previousReversePointer is this one
}else //after the first loop, the previous ReversePointer will be set
{
revNode->data = currentPtr->data; //set it's data to the pointer's data
revNode->nextPtr = prevRevPtr; //reverseNode's pointer points to last node entered
currentPtr = currentPtr->nextPtr; //moves to next letter
prevRevPtr = revNode; //changes previous reverse node to current node
if(counter == 10)//on the last loop...
{
revStart = revNode; //set revStart as a pointer to the last reverse node
//which is technically the "first"
}
}
}
}
return revStart;
}
Assuming your list is properly wired from inception, reversing a double-linked list is basically this:
Node *reverse(Node *stPtr)
{
Node *lst = stPtr, *cur = stPtr;
while (cur)
{
Node *tmp = cur->nextPtr;
cur->nextPtr = cur->prevPtr;
cur->prevPtr = tmp;
lst = cur;
cur = tmp;
}
return lst;
}
That's it . All this does is walk the list, swapping pointers, and retaining whatever the last node processed was. When done correctly the list will still be end-terminated (first node 'prev' is null, last node 'next' is null, and properly wired between.
I strongly advise walking a list enumeration through this function in a debugger. With each iteration watch what happens to cur as it marches down the list, to the active node's nextPtr and prevPtr values as their swapped, and to lst, which always retains the last-node processed. It's the new list head when done.
Okay so we don't need to contend with no line breaks in commments:
Node *reverse(Node *list) {
Node *rev = NULL;
while (list) {
Node *elt = list; // pop from the list
list = list->next;
elt->next = rev; // push onto reversed list.
rev = elt;
}
return rev;
}
As you wrote in comments, you probably don't need to have a previous pointer; you can just create a singly linked list.
There are several issues in your code, including:
When malloc returns NULL, you still continue with the loop -- only part of the code is protected by the if that follows, but not the rest. You should probably just exit the program when this happens.
Your algorithm does not maintain a reference to the very first node, i.e. the place where the linked list starts. When you print the list you should start with the first node of the list, but instead you start with newNode, which is the last node you created, so obviously not much will be printed except that last node. Moreover, both other pointers you have, will also point to the last node (currentPtr, previousPtr) when the loop ends.
newNode->nextPtr = newNode; temporarily creates an infinite cycle in your list. This is resolved in the next iteration of the loop, but it is unnecessary to ever make the list cyclic.
In the reverse function you have if(prevRevPtr = NULL)... You should get a warning about that, because that is an assignment, not a comparison.
Some other remarks:
The reverse function unnecessarily makes distinction between dealing with the first node and the other nodes.
It is also not nice that it expects the list to have 10 nodes. It would be better to just rely on the fact that the last node will have a NULL for its nextPtr.
It is a common habit to call the first node of a linked list, its head. So naming your variables like that is good practice.
As you are required to print both the initial list and the reversed list, it would be good to create a function that will print a list.
As you need to create new nodes both for the initial list and for the reversed list, it would be good to create a function that will create a node for you.
(I know that your teacher asked to create only one function, but this is just best practice. If this doesn't fit the assignment, then you'll have to go with the malloc-related code duplication, which is a pitty).
As you defined the type NodePtr, it is confusing to see a mix of Node* and NodePtr in your code.
Your question was first not clear on whether the reversal of the list should be in-place or should build a new list without tampering with the initial list. From comments it became clear you needed a new list.
I probably didn't cover all problems with the code. Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
struct charNode {
char data;
struct charNode *nextPtr;
};
typedef struct charNode Node;
typedef Node *NodePtr;
NodePtr reverse(Node *stPtr);
void printList(Node *headPtr);
NodePtr createNode(int data, NodePtr nextPtr);
int main(void) {
NodePtr headPtr = NULL; // You need a pointer to the very first node
NodePtr tailPtr = NULL; // Maybe a better name for currentPtr
printf("Enter 10 letters to make a list: ");
for (int counter = 0; counter < 10; counter++) {
char input;
scanf("%c", &input);
NodePtr newNode = createNode(input, NULL);
if (headPtr == NULL) {
headPtr = newNode;
} else {
tailPtr->nextPtr = newNode;
}
tailPtr = newNode;
}
NodePtr revHeadPtr = reverse(headPtr);
puts("The list is:\n");
printList(headPtr);
puts("The reversed list is:\n");
printList(revHeadPtr);
}
void printList(NodePtr headPtr) {
while (headPtr != NULL) {
printf("%c --> ", headPtr->data);
// You can just move the head pointer: it is a variable local to this function
headPtr = headPtr->nextPtr;
}
puts("NULL\n");
}
NodePtr createNode(int data, NodePtr nextPtr) {
NodePtr newNode = malloc(sizeof(Node));
if (newNode == NULL) { // If malloc fails, exit the program
puts("Cannot allocate memory\n");
exit(1);
}
newNode->data = data;
newNode->nextPtr = nextPtr;
return newNode;
}
NodePtr reverse(NodePtr headPtr) {
NodePtr revHeadPtr = NULL;
while (headPtr != NULL) {
revHeadPtr = createNode(headPtr->data, revHeadPtr);
// You can just move the head pointer: it is a variable local to this function
headPtr = headPtr->nextPtr;
}
return revHeadPtr;
}
I'm trying to do an insertion sort on a doubly linked list in C. in this state, my code gets me stuck in an non-ending loop spitting out 8s and 9s.
can someone please be kind enough to explain how the "insertionSort" method is supposed to be designed?
my linked list is designed containing head, previous, next and some data.
Here is my code so far
My hope is NULL. please help.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
struct Node* previous;
}Node;
struct Node* head = NULL;
struct Node* current = NULL;
struct Node* headsorted = NULL;
int l = 0;
int empty = 1;
int length = 0;
int change = 0;
void InsertSort(){
Node* temp = (Node*)malloc(sizeof(struct Node));
temp = head;
current = head->next;
printf("\nInsert Sort begins...\n");
if (head != NULL && head->next != NULL)
{
for (int i = 1; i < length; i++)
{
while(current->data > current->next->data && current->next != NULL && current != NULL)
{
temp = current;
current = current->next;
current->next = temp;
}
}
}
else
{
printf("\nList Error!\n");
}
temp = NULL;
}
void Insert(int x)
{
Node* temp = (Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next = head;
temp->previous = NULL;
if (head != NULL)
{
head->previous = temp;
}
head = temp;
}
void Print(){
struct Node* temp = head;
printf("List is: ");
while(temp != NULL)
{
printf(" %d", temp->data);
temp = temp->next;
}
}
int main()
{
head = NULL;
FILE * file = fopen("List.txt", "r");
fscanf(file, "%d", &l);
while (!feof (file))
{
Insert(l);
fscanf(file, "%d", &l);
length++;
}
fclose(file);
Print();
printf("\n\n\n");
printf("data: %d next: %d " , head->data, head->next->data);
InsertSort();
Print();
return 0;
}
can someone please be kind enough to explain how the "insertionSort"
method is supposed to be designed?
In the first place, I suggest getting rid of the length variable, or at least not using it in your sort routine. It is not needed, and relying on it may be diverting your thinking too much toward array-style implementations. You know you've reached the end of the list when you discover a node whose next pointer is NULL.
Secondly, I reiterate my comment that you are not performing node swaps correctly for a doubly-linked list. A node swap on any linked list, whether singly- or doubly-linked, is equivalent to extracting the second node from the list altogether, then reinserting it before the first. In a singly-linked list that affects, in general, three nodes: in addition to the two being swapped, the predecessor to the first. In a doubly-linked list, it also affects the successor to the second. That's messy enough in the doubly-linked case that I suggest structuring it explicitly as an excision followed by an insertion.
But I also suggest that you take a step back and look at the algorithm from a high level. It works by considering each node in turn, starting with the second, and if necessary removing it and reinserting it at its correct position in the (sorted) sublist preceding it. So what, then, does pairwise swapping even have to do with it? Nothing. That's a detail convenient in implementing such a sort on an array, but it makes needless work when sorting a linked list.
For a linked list, especially a doubly-linked one, I suggest an implementation cleaving more directly to the abstract description of the algorithm:
Maintain a pointer, S, to the last node of the sorted leading sublist. Initially, this will point to the list head.
If S points to the last node (which you can judge by S->next) then stop.
Otherwise, check whether *N, the successor to *S, is correctly ordered relative to *S.
If so, then set S (the pointer, not its referrent) equal to N.
If not, then
cut the *N from the list (updating both its predecessor and its successor, if any, appropriately), and
step backward through the sorted sublist until you reach either the first node or one whose predecessor should precede *N, whichever is encountered first.
Insert *N before the node you've discovered.
If that makes *N the list head (which you can judge by the new value of its previous pointer), then set the head pointer (not its referrent) equal to N.
repeat from point 2
The actual code is left as the exercise it is intended to be.
I am having problems with my huffman tree; when I try to build it I get the nodes in the wrong place. For example, I want my node of weight 2 (with children i:1 and n:1) to go in between a node of m:2 and space:3 but instead it goes right after the previous node that I put in (2 with children of e:1 and g:1).
My question is: how do I insert a node with two children into a huffman tree (I am using a linked list) by priority of both it's weight (aka the sum of both its children) and the symbols of the children (i.e. the right child 'n' comes before the other right child of 'g').
Thanks for your help!
EDIT: also, how can I print off the codes of the tree in alphabetical order; right now I have them printing off by rightmost tree to leftmost
Here is my insert function...
struct node* insert(struct node* head, struct node* temp)
{
struct node* previous = NULL;
struct node* current = head;
printf("entering insert function\n");
// finds the previous node, where we want to insert new node
while (temp->freq > current->freq && current->next != NULL)
{
printf("traversing: tempfreq is %lu and currentfreq is %lu\n", temp->freq, current->freq);
previous = current;
current = current->next;
}
if (current->next == NULL)
{
printf("hit end of list\n");
temp = current->next;
}
else
{
printf("inserting into list\n");
temp->next = current;
previous->next = temp;
}
return head;
}
You've got the insertion wrong when you hit the end of the list. This:
temp = current->next;
should be the other way round, otherwise you just assign NULL to a temporary variable, which won't do anything to your list.
But I think that you also got your special cases wrong. The special case is not "insert at the end", but "insert a new head". Your code will fail if head == NULL. (This might not happen, because you have already a list of nodes without children and you remove nodes until only one node is left, but still.)
A better implementation might therefore be:
struct node *insert(struct node *head, struct node *temp)
{
struct node *previous = NULL;
struct node *current = head;
while (current && temp->freq > current->freq) {
previous = current;
current = current->next;
}
if (previous == NULL) {
temp->next = head;
return temp;
}
temp->next = current;
previous->next = temp;
return head;
}
Note how this code never derefeneces current or previous when they are NULL. Your special case "insert at the end" is handled by the regular code when current == NULL.
Edit: Concerning your request to print the nodes in alphabetical order: There are many possibilities to do that. One is to add a char buffer to your structure that contains the encoding for the letter:
struct node {
int value;
unsigned long freq;
struct node *next;
struct node *left;
struct node *right;
char code[32];
};
Then you create an "alphabet", i.e a list of 256 pointers to nodes of your Huffman tree, initially all null. (You'll need that alphabet for encoding anyways.)
struct node *alpha[256] = {NULL};
Then traverse your tree, pass a temporary char buffer and assign nodes to your alphabet as appropriate:
void traverse(struct node *n, int level, char buf[], struct node *alpha[])
{
if (n == NULL) return;
if (n->value) {
alpha[n->value] = n;
strcpy(n->code, buf);
} else {
buf[level] = '0';
traverse(n->left, level + 1, buf, alpha);
buf[level] = '1';
traverse(n->right, level + 1, buf, alpha);
}
}
When the node has a value, i.e. is childless, the value (ASCII code) is assigned to the alphabet, so that alpha['a'] points to the node with value 'a'. Note that the alphabet does not create nodes, it points to existing nodes.
Finally, print the alphabet:
char buf[32];
traverse(head, 0, buf, alphabet);
for (i = 0; i < 256; i++) {
if (alpha[i] != NULL) {
printf("%c: %s\n", alpha[i]->value, alpha[i]->code);
}
}
Please note that 32 is n arbitrary value that is chosen to be high enough for the example. In a real tree, memory for the code might be allocated separately.
if i have a reference to an element in a linked list, how do i swap it with the next element, in c
here's a try,
Node* nRoot, *temp=pNode->next;
nRoot=pNode;
do{
nRoot->next = temp->next;
if(nRoot==pNode) pNode=temp;
temp->next = nRoot;
nRoot=nRoot->next;
}while(nRoot!=NULL)||temp!=NULL);
but it does not work
You can only do this if it double linked list. You need the previous pointer so that you can point it's next to the current's next.
However if you have these then you an do something like this:
Node* next = curr->next;
Nide* prev = curr->prev;
curr->prev = next;
curr->next = next->next;
curr->next->prev = curr;
next->prev = prev;
next->prev->next = next;
next->next = curr;
And the 2 are swapped.
Edit: Of course you can do this with a singly linked list but you do need to know the previous node so that you fix up its next pointer to point to the current's next.
If you have a reference to A and A->next is B, you can do this. I'm assuming they hold a Data* pointer, replace with whatever the data is. Don't actually swap the nodes, just swap the data in the nodes.
void push_forward(Node* curr)
{
Data* currData = curr->data;
curr->data = curr->next->data;
curr->next->data = currData;
}
For the record, I am not a C guy so this might be correct only in algorithm, but not in implementation. I welcome edits, fixes, suggestions, and constructive comments!
If there are no external pointers to the elements that you wish to swap, then you can just swap the data within the list nodes, rather than the nodes themselves, as pointed out in other answers.
If you have external pointers to the list nodes, then you should probably not mess with the node content, unless the rest of your program is find with node contents changing from under its feet.
You will have to swap the nodes, which means that you need to have a pointer to the node that precedes the ones that you need to swap. If you only have the head of the list, then the swap function could be something along these lines:
void swap(Node **list, Node *first) {
Node *i = *list;
Node *p = NULL;
while (i != NULL) {
if (i == first) {
Node *n = i->next;
/* No next node to swap with */
if (n == NULL)
break;
if (p != NULL) {
p->next = n;
} else {
*list = n;
}
i->next = n->next;
n->next = i;
break;
}
p = i;
i = i->next;
}
}