This function here interchanges nodes in a linked list
Here is what I have so far:Code:void interchangeNodes(nodeptr&head, int n, int m);
Where I am getting stuck is this, maybe my whole function is wrong also, interchange 2 adjacent nodes... otherwise, advance temp2 to point to n - 1st node. Then temp2 will be the new node and once again set the 1st node to point to n + 1st nodes. Easy... I thought, until I first ran what I have so far and see that I am in an infinite loop. And so then I broke down and quit for this while being. Can help please be given here?Code:void interchangeNodes(nodeptr& head, int n, int m) { nodeptr temp = head; nodeptr temp2; int i = 1; if(temp == NULL || temp->next == NULL) //nothing happens if either is null value return; if(n == m) //nothin happens if n node is equal to m node return; if(n < m){ //swap the two if n is less then m int temp; temp = n; m = m; temp = m; } if(m == 1) { temp = temp->next; //if n = 1, interchange first node and nth node temp2 = head; if(n == 2) { //interchange first two nodes head = head->next; temp->next = head->next; head->next = temp; } } else //otherwise, advance temp to n - 1st node... do nothing if next is of null { while(i < n - 1) { if(temp->next == NULL) return; else temp = temp->next; i++; } temp2 = temp->next; //temp2 is nth node //set 1st node to point to n + 1st node temp2->next = head->next; temp->next = head; head = temp2; } if(m > 1){ while(i < m - 1){ //advance temp to point to m - 1st node, do nothing if next is of null if(temp->next == NULL) return; else temp = temp->next; i++; } } }



LinkBack URL
About LinkBacks


