How do I sort Linked list based on the length of strings? [duplicate] - c++

I have been struggling for hours on end with this problem. My goal is to sort a linked list using only pointers (I cannot place linked list into vec or array and then sort). I am given the pointer to the head node of the list. The only methods i can call on the pointers are head->next (next node) and head->key (value of int stored in node, used to make comparisons). I have been using my whiteboard excessively and have tried just about everything I can think of.
Node* sort_list(Node* head)
{
Node* tempNode = NULL;
Node* tempHead = head;
Node* tempNext = head->next;
while(tempNext!=NULL) {
if(tempHead->key > tempNext->key) {
tempNode = tempHead;
tempHead = tempNext;
tempNode->next = tempNode->next->next;
tempHead->next = tempNode;
tempNext = tempHead->next;
print_list(tempHead);
}
else {
tempHead = tempHead->next;
tempNext = tempNext->next;
}
}
return head;
}

Since it's a singly linked list, we can do: (psuedo code)
bool unsorted = true;
while(unsorted) {
unsorted = false;
cur = head;
while(cur != nullptr) {
next = cur->next;
if(next < cur) {
swap(cur, next)
unsorted = true;
}
cur = cur->next;
}
}

I know its late but I also search for it but didn't get one so I make my own. maybe it will help someone.
I am using bubble sort (kind of sort algorithm) to sort data in a single linked list. It just swapping the data inside a node.
void sorting(){
Node* cur1 = head;
Node* cur2 = head;
for (int i = 0; i < getSize(); i++) {
for (int j = 0; j < getSize() - 1; j++) {
if (cur1->data < cur2->data) {
int temp = cur1->data;
cur1->data = cur2->data;
cur2->data = temp;
}
cur2 = cur2->next;
}
cur2 = head;
cur1 = head->next;
for (int k = 0; k < i; k++) {
cur1 = cur1->next;
}
}
}

Don't feel bad this is a lot harder than it sounds. If this were in an array it would be considerably easier. If the list were doubly linked it would be easier. Take a look at this code, it implements an insertion sort
struct Node {
int key;
Node *next;
} *NodePtr;
// do a simple selection sort http://en.wikipedia.org/wiki/Selection_sort
Node* sort_list(Node* head) {
Node *top = nullptr; // first Node we will return this value
Node *current = nullptr;
bool sorted = false;
while (sorted == false) {
// we are going to look for the lowest value in the list
Node *parent = head;
Node *lowparent = head; // we need this because list is only linked forward
Node *low = head; // this will end up with the lowest Node
sorted = true;
do {
// find the lowest valued key
Node* next = parent->next;
if (parent->key > next->key) {
lowparent = parent;
low = next;
sorted = false;
}
parent = parent->next;
} while (parent->next != nullptr);
if (current != nullptr) { // first time current == nullptr
current->next = low;
}
// remove the lowest item from the list and reconnect the list
// basically you are forming two lists, one with the sorted Nodes
// and one with the remaining unsorted Nodes
current = low;
if (current == head) { head = current->next; }
lowparent->next = low->next;
current->next = nullptr;
if (top == nullptr) {
top = current;
}
};
current->next = head;
return top;
}
int _tmain(int argc, _TCHAR* argv []) {
Node nodes[4];
nodes[0].key = 3;
nodes[1].key = 4;
nodes[2].key = 5;
nodes[3].key = 1;
nodes[0].next = &nodes[1];
nodes[1].next = &nodes[2];
nodes[2].next = &nodes[3];
nodes[3].next = nullptr;
auto sortedNodes = sort_list(&nodes[0]);
return 0;
}

Use a recursive approach as it is the easiest way of dealing with linked structures:
Pseudocode:
SORT(head)
if (head->next == null)
return
tempNode = head->next
SORT(tempNode)
if (tempNode->value < head->value)
SWAP(head, tempNode)
SORT(head)
return
so the let's say you have 5 4 3 2 1
1) 5 4 3 1 2
2) 5 4 1 3 2
3) 5 4 1 2 3
4) 5 1 4 2 3
5) 5 1 2 4 3
...
n) 1 2 3 4 5

Assume the Node like this:
struct Node
{
Node *next;
int key;
Node(int x) : key(x), next(NULL) {}
};
use insertion sort algorithm to sort the List:
Node* sort_list(Node* head)
{
Node dumy_node(0);
Node *cur_node = head;
while (cur_node)
{
Node *insert_cur_pos = dumy_node.next;
Node *insert_pre_pos = NULL;
while (insert_cur_pos)
{
if (insert_cur_pos->key > cur_node->key)
break;
insert_pre_pos = insert_cur_pos;
insert_cur_pos = insert_cur_pos->next;
}
if (!insert_pre_pos)
insert_pre_pos = &dumy_node;
Node *temp_node = cur_node->next;
cur_node->next = insert_pre_pos->next;
insert_pre_pos->next = cur_node;
cur_node = temp_node;
}
return dumy_node.next;
}

int swapNode( node * &first, node * &second)
{
//first we will declare the
//previous of the swaping nodes
node *firstprev=NULL;
node*secprev=NULL;
node*current=head;
//set previous first
while(current->next!=first)
{
current=current->next;
}
firstprev=current;
//seting 2nd previous
while(current->next!=second)
{
current=current->next;
}
// swap datas, assuming the payload is an int:
int tempdata = first->data;
first->data = second->data;
second->data = tempdata;
//swaping next of the nodes
firstprev->next=second;
secprev->next=first;
}

Here is my Merge sort realisation, with O(N*logN) time complexity and constant additional space. Uses C++11
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
typedef pair<ListNode*, ListNode*> PP;
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (head==nullptr)return head;
if (head->next==nullptr) return head;
if (head->next->next==nullptr){
if (head->val<=head->next->val){
return head;
}
else {
ListNode* second=head->next;
second->next=head;
head->next=nullptr;
return second;
}
}else {
PP splitted=split(head);
return merge(sortList(splitted.first),sortList(splitted.second));
}
}
private:
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode * head=new ListNode(0);
ListNode * current=head;
if (l1==nullptr)return l2;
if (l2==nullptr)return l1;
do {
if (l1->val<=l2->val){
current->next=l1;
l1=l1->next;
}else{
current->next=l2;
l2=l2->next;
}
current=current->next;
}while (l1!=nullptr && l2!=nullptr);
if (l1==nullptr)current->next=l2;
else current->next=l1;
return head->next;
}
PP split(ListNode* node){
ListNode* slow=node;
ListNode* fast=node;
ListNode* prev;
while(fast!=nullptr){
if (fast->next!=nullptr){
prev=slow;
slow=slow->next;
fast=fast->next;
}else break;
if(fast->next!=nullptr){
fast=fast->next;
}
else break;
}
prev->next=nullptr;
return {node,slow};
}
};

Use std::list<T>::sort method. Or if you're being precocious, std::forward_list<T>::sort.
Why re-invent the wheel.

Related

can I sort a linked-list by an inherited class in c++?

I implemented a linked list in a class with addToHead, addToTail, deleteFromHead, deleteFromTail, isEmpty, and display functions, and I want to sort the linked list in ascending order in an inherited class, so I made a class TSortedList with two functions; the sortList function that compares the elements of the linked list with each other, and the display() function that display the linked list after sorting it. But when I run the code nothing appear to me, however when I sort it through a function in the parent class, not the inherited class it works, so I do not know where is the problem
#include <iostream>
using namespace std;
class Node {
public:
Node() {
next = 0;
//write your modification here
}
Node(int el, Node *ptr = 0) { //write your modification for the constructor arguments here
info = el;
next = ptr;
}
int info;
Node *next;
//write your modification here
};
class LList {
protected:
Node *head, *tail;
public:
LList() {
head = tail = 0;
}
~LList(){
for (Node *p; !isEmpty(); ) {
p = head->next;
delete head;
head = p;
}
}
int isEmpty() {
return head == 0;
}
virtual void addToHead(int el){
head = new Node(el,head);
if (tail == 0)
tail = head;
}
virtual void addToTail(int el){
if (tail != 0) { // if list not empty;
tail->next = new Node(el);
}
else head = tail = new Node(el);
}
int deleteFromHead(){ // delete the head and return its info;
int el = head->info;
Node *tmp = head;
if (head == tail) // if only one node in the list;
head = tail = 0;
else head = head->next;
delete tmp;
return el;
}
int deleteFromTail(){ // delete the tail and return its info;
int el = tail->info;
if (head == tail) { // if only one node in the list;
delete head;
head = tail = 0;
}
else { // if more than one node in the list,
Node *tmp; // find the predecessor of tail;
for (tmp = head; tmp->next != tail; tmp = tmp->next);
delete tail;
tail = tmp; // the predecessor of tail becomes tail;
tail->next = 0;
}
return el;
}
bool isInList(int el) const{
Node *tmp;
for (tmp = head; tmp != 0 && !(tmp->info == el); tmp = tmp->next);
return tmp != 0;
}
virtual void displayList(){
if (head == 0) // if empty list;
return;
Node *tmp = head;
for (tmp = head; tmp != 0; tmp = tmp->next){
cout<<tmp->info<<endl;
}
}
};
class TSortedList: public LList, public Node
{
protected:
Node *current = head, *index = 0;
int temp;
public:
void sortList() {
if(head == 0) {
return;
}
else {
while(current != 0) {
//Node index will point to node next to current
index = current->next;
while(index != 0) {
//If current node's data is greater than index's node data, swap the data betweenthem
if(current->info > index->info) {
temp = current->info;
current->info = index->info;
index->info = temp;
}
index = index->next;
}
current = current->next;
}
}
}
void display() {
//Node current will point to head
Node *current = head;
if(head == 0) {
return;
}
while(current != 0) {
//Prints each node by incrementing pointer
cout<<current->info<<endl;
current = current->next;
}
cout<<"\n"<<endl;
}
};
int main()
{
//Adds data to the list
LList myList;
myList.addToHead(1);
myList.addToHead(7);
myList.addToHead(3);
TSortedList sortt;
sortt.sortList();
sortt.display();
return 0;
}
Your TSortedList sortt; is empty; you never add anything to it.
What do you expect it to display?
This should work as you expected:
int main()
{
//Adds data to the list
TSortedList myList;
myList.addToHead(1);
myList.addToHead(7);
myList.addToHead(3);
myList.display(); // this should be in original order
myList.sortList();
myList.display(); // this should be sorted
return 0;
}
Also, why are you deriving your TSortedList from Node?
class TSortedList: public LList, public Node

How can I partition a singly linked list around a value, using two seperate functions in main() - one lesserThan and the other greaterThan - in C/C++

I have the following linked list:
2->1->9->8->3->1->nullptr.
I want to partition the linked list around the value 4, such that all values less than 4, come before all values greater than or equal to 4.
I can partition the linked list using a single function. But, I want to do it using two function - a function lesserThan(head,x) and a function greaterThan(head, x) - where x is the value around which I want to partition the list.
But, I am running into the following problem: If I use both functions together, the list nodes are modified by the first function - and, the second function works on that modified nodes. The functions work fine, when the other one is commented out. That is, lesserThan(head,x) works fine, when greaterThan(head, x) is commented out, and vice-versa.
How can I partition the linked list, by still using both the functions in main()? The main problem I am having is that the nodes are getting modified in both lesserThan and greaterThan functions, and that is getting reflected in main().
Following is the code:
struct Node
{
int data;
Node* next;
};
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->next = nullptr;
return temp;
}
Node* lesserThan(Node* head, int x)
{
if (head == nullptr)
{
return nullptr;
}
Node* list1=nullptr, *temp1 = nullptr;
if ((head)->data < x)
{
temp1=list1 = head;
}
else
{
while (head && head->data >= x)
{
head = head->next;
}
if (head && head->data < x)
{
temp1 = list1 = head;
}
}
Node* curr = temp1;
if(curr)
curr = curr->next;
while (curr)
{
Node* next = curr->next;
if (curr->data<x)
{
list1->next = curr;
list1 = curr;
list1->next = nullptr;
}
curr = next;
}
return temp1;
}
Node* greaterThan(Node* head, int x)
{
Node* temp2 = nullptr, *list2=nullptr;
if (head->data >= x)
{
temp2 =list2= head;
}
else
{
while (head && head->data < x)
{
head = head->next;
}
if (head && head->data >= x)
{
temp2 = list2 = head;
}
}
Node* curr = list2;
if (curr)
curr = curr->next;
while (curr)
{
Node* next = curr->next;
if (curr->data >= x)
{
list2->next = curr;
list2 = curr;
list2->next = nullptr;
}
curr = next;
}
return temp2;
}
int main()
{
Node* head = newNode(2);
head->next = newNode(1);
head->next->next = newNode(9);
head->next->next->next = newNode(8);
head->next->next->next->next = newNode(3);
head->next->next->next->next->next = newNode(1);
int x = 4;
Node* p1 = lesserThan(head,x);
Node* p2 = greaterThan(head, x);
if (p1 != nullptr)
p1->next = p2;
while (p1)
{
cout << p1->data << " ";
p1 = p1->next;
}
cout << endl;
return 0;
}
Following are the two functions, that fail to work together, because the List nodes are modified by the first function (and second function), and that is reflected in main() -
How can I have the two functions in main, so that they don't effect each other? I tried creating different variables for head, and passing them to the functions. But that didn't work. Thanks for the help!
It will be better to use insert recursive function instead of your style and note that you have undeleted allocated nodes. I didn't consider them. Any way, I think the following code works as intented
struct Node
{
Node() = default;
Node( int dataVal ):data{dataVal}{}
int data{};
Node* next{};
};
Node*& lessThan( Node* const & head, int x){
if( !head ) throw std::invalid_argument("Empty linked list");
Node* toBeReturned;
Node* currentHeadNode = head;
Node** currentReturned = & toBeReturned;
while( currentHeadNode ){
if(currentHeadNode -> data < x ){
*currentReturned = new Node{ currentHeadNode -> data };
currentReturned = &((*currentReturned) -> next);
}
currentHeadNode = currentHeadNode->next;
}
return toBeReturned;
}
int main()
{
Node* head = new Node(2);
head->next = new Node(1);
head->next->next = new Node(9);
head->next->next->next = new Node(8);
head->next->next->next->next = new Node(3);
head->next->next->next->next->next = new Node(1);
int x = 4;
Node* p1 = lessThan(head,x);
while (p1)
{
std::cout << p1->data << " ";
p1 = p1->next;
}
std::cout << std::endl;
return 0;
}

Function moving list elements to the end of the list not working multiple times

I need to make a function that moves the nth element in a singly linked list to the end of the list. I created some code that does that but it only works once if I try to do it again it moves the selected element to the end but the one that was moved previously gets deleted/dissapears. My theory is that it doesnt actually change the tail reference. so im stuck right now!
void move(int n)
{
if (head == NULL || head->next == NULL)
{
return;
}
node *first = head;
node *temp =new node;
for (int i = 1; i < n-1; i++)
{
first=first->next;
}
temp = first->next;
first->next=first->next->next;
temp->next = NULL;
tail->next = temp;
tail=temp;
}
my input:
1 2 3 4 5
after moving the 3rd element for the first time:
1 2 4 5 3
after moving the 3rd element(4) for the 2nd time:
1 2 5 4
but it should be
1 2 5 3 4
I checked your code with my own implementation. Your function move() is working fine. However, you should not be using 'new' in your 8th line of code as highlighted by #molbdnilo and #PaulMakenzie. But it is not responsible for this problem. There is a problem with some other part of your code.
#include<iostream>
using namespace std;
class List
{
struct Node
{
int number;
Node* next;
};
Node* head;
Node* tail;
public:
List()
{
head = NULL;
tail = NULL;
}
void insert(int num)
{
Node* temp = new Node();
temp->number = num;
temp->next = NULL;
if (head == NULL)
{
head = temp;
tail = temp;
}
else
{
Node* point = head;
while (point->next != NULL)
point = point->next;
point->next = temp;
tail = point->next;
}
}
void display()
{
Node* point = head;
while (point != NULL)
{
cout << point->number << " ";
point = point->next;
}
}
void move(int n)
{
if (head == NULL || head->next == NULL)
{
return;
}
Node *first = head;
Node *temp;
for (int i = 1; i < n-1; i++)
{
first=first->next;
}
temp = first->next;
first->next=first->next->next;
temp->next = NULL;
tail->next = temp;
tail=temp;
}
};
int main()
{
List a;
a.insert(1);
a.insert(2);
a.insert(3);
a.insert(4);
a.insert(5);
a.move(3);
a.move(3);
a.display();
}

Sorting a linked list using Quicksort in C++

I was reading about Quicksort, and most of the codes I found were extremely complicated. So, I decided to make one on my own, wherein I considered the first element as pivot and then calling sort function recursively on the rest of the list.
I made the following code for Quicksort. It's as follows:
#include <iostream>
using namespace std;
class node
{
public:
int data;
node * next;
};
node * newnode (int x);
void quicksort(node ** begin, node ** end);
int main (void)
{
int foo,n,i,j,k;
node * temp;
node * head = NULL;
node * tail = NULL;
cout<<"How many nodes do you want to insert\n";
cin>>n;
cout<<"Enter data of linked list\n";
for ( i = 0; i < n; i++ )
{
cin>>foo;
node * bar;
if (head == NULL)
{
head = newnode(foo);
tail = head;
}
else
{
bar = newnode(foo);
tail->next = bar;
tail = bar;
}
}
cout<<"The linkedlist that you entered is as follows\n"; // Taking input
temp = head;
node * prev = NULL;
while (temp != NULL)
{
cout<<temp->data<<"\t";
prev = temp;
temp = temp->next;
}
cout<<"\n";
cout<<"Sorting the linked list now\n"; // Calling sort function
quicksort(&head,&prev);
temp = head;
while (temp != NULL) // Printing output
{
cout<<temp->data<<"\t";
temp = temp->next;
}
return 0;
}
node * newnode (int x) // for allocating a new node
{
node * foo = new node;
foo->data = x;
foo->next = NULL;
return foo;
}
void quicksort(node ** begin, node ** end) // actual sort function
{
if (*begin == *end)
return;
node * pivot = *begin;
node * temp = *begin;
temp = temp->next; // for pointing to next element
while (temp != *end)
{
if (temp->data < pivot->data)
{
node * temp1 = *begin; // swapping the two nodes if less than pivot
*begin = temp;
temp = temp->next;
(*begin)->next = temp1;
}
else
temp = temp->next; else moving to next
}
quicksort(begin,&pivot); // calling for remaining elements (first half)
quicksort(&(pivot->next),end); for second half
}
Howeever, when I run this, on input as 5 4 3 2 1, it sort of goes into an infinite loop. I tried running it through a debugger, but it get's extremely complicated to the extent that I lose my way in between. Can you point out the error where I might be going wrong? Thanks!

Reverse doubly-link list in C++

I've been trying to figure out how to reverse the order of a doubly-linked list, but for some reason, in my function void reverse() runs while loop once and then crashes for some reason. To answer some questions ahead, I'm self-teaching myself with my brothers help. This isn't all of the code, but I have a display() function which prints all nodes chronologically from start_ptr and a switch which activates certain functions like
case 1 : add_end(); break;
case 2 : add_begin(); break;
case 3 : add_index(); break;
case 4 : del_end(); break;
case 5 : del_begin(); break;
case 6 : reverse(); break;
This is the geist of my code:
#include <iostream>
using namespace std;
struct node
{
char name[20];
char profession[20];
int age;
node *nxt;
node *prv;
};
node *start_ptr = NULL;
void pswap (node *pa, node *pb)
{
node temp = *pa;
*pa = *pb;
*pb = temp;
return;
}
void reverse()
{
if(start_ptr==NULL)
{
cout << "Can't do anything" << endl;
}
else if(start_ptr->nxt==NULL)
{
return;
}
else
{
node *current = start_ptr;
node *nextone = start_ptr;
nextone=nextone->nxt->nxt;
current=current->nxt;
start_ptr->prv=start_ptr->nxt;
start_ptr->nxt=NULL;
//nextone=nextone->nxt;
while(nextone->nxt!= NULL)
{
pswap(current->nxt, current->prv);
current=nextone;
nextone=nextone->nxt;
}
start_ptr=nextone;
}
}
Try this:
node *ptr = start_ptr;
while (ptr != NULL) {
node *tmp = ptr->nxt;
ptr->nxt = ptr->prv;
ptr->prv = tmp;
if (tmp == NULL) {
end_ptr = start_ptr;
start_ptr = ptr;
}
ptr = tmp;
}
EDIT: My first implementation, which was correct but not perfect.
Your implementation is pretty complicated. Can you try this instead:
node * reverse(Node * start_ptr)
{
Node *curr = start_ptr;
Node * prev = null;
Node * next = null;
while(curr)
{
next = curr->nxt;
curr->nxt = prev;
curr->prv = next;
prev = curr;
curr = next;
}
return start_ptr=prev;
}
Here is my updated solution:
node * reverse()
{
node *curr = start_ptr;
node * prev = NULL;
node * next = NULL;
while(curr)
{
next = curr->nxt;
curr->nxt = prev;
curr->prv = next;
prev = curr;
curr = next;
}
return start_ptr=prev;
}
The logic was correct. But the issue was that I was accepting in input argument start_ptr. Which means that I was returning the local copy of it. Now it should be working.
You can simplify your reverse() quite a bit. I'd do something like this:
void reverse()
{
if(start_ptr == NULL)
{
cout << "Can't do anything" << endl;
}
else
{
node *curr = start_ptr;
while(curr != NULL)
{
Node *next = curr->next;
curr->next = curr->prev;
curr->prev = next;
curr = next;
}
start_ptr = prev;
}
}
Explanation: The basic idea is simply to visit each Node and swap the links to previous and next. When we move curr to the next Node, we need to store the next node so we still have a pointer to it when we set curr.next to prev.
Simple solution. reverses in less than half a number of total iterations over the list
template<typename E> void DLinkedList<E>::reverse() {
int median = 0;
int listSize = size();
int counter = 0;
if (listSize == 1)
return;
DNode<E>* tempNode = new DNode<E>();
/**
* A temporary node for swapping a node and its reflection node
*/
DNode<E>* dummyNode = new DNode<E>();
DNode<E>* headCursor = head;
DNode<E>* tailCursor = tail;
for (int i = 0; i < listSize / 2; i++) {
cout << i << "\t";
headCursor = headCursor->next;
tailCursor = tailCursor->prev;
DNode<E>* curNode = headCursor;
DNode<E>* reflectionNode = tailCursor;
if (listSize % 2 == 0 && listSize / 2 - 1 == i) {
/**
* insert a dummy node for reflection
* for even sized lists
*/
curNode->next = dummyNode;
dummyNode->prev = curNode;
reflectionNode->prev = dummyNode;
dummyNode->next = reflectionNode;
}
/**
* swap the connections from previous and
* next nodes for current and reflection nodes
*/
curNode->prev->next = curNode->next->prev = reflectionNode;
reflectionNode->prev->next = reflectionNode->next->prev = curNode;
/**
* swapping of the nodes
*/
tempNode->prev = curNode->prev;
tempNode->next = curNode->next;
curNode->next = reflectionNode->next;
curNode->prev = reflectionNode->prev;
reflectionNode->prev = tempNode->prev;
reflectionNode->next = tempNode->next;
if (listSize % 2 == 0 && listSize / 2 - 1 == i) {
/**
* remove a dummy node for reflection
* for even sized lists
*/
reflectionNode->next = curNode;
curNode->prev = reflectionNode;
}
/**
* Reassign the cursors to position over the recently swapped nodes
*/
tailCursor = curNode;
headCursor = reflectionNode;
}
delete tempNode, dummyNode;
}
template<typename E> int DLinkedList<E>::size() {
int count = 0;
DNode<E>* iterator = head;
while (iterator->next != tail) {
count++;
iterator = iterator->next;
}
return count;
}
I suggest maintaining a link to the last node.
If not, find the last node.
Traverse the list using the "previous" links (or in your case, prv).
There is no need to actually change the links around. Traversing using the prv pointer will automatically visit the nodes in reverse order.
Look at
valuesnextone=nextone->nxt->nxt;
Here nextone->nxt can be null.
Apart from that, try to use pointers to pointers in the swap function.
Your pswap function is wrong
your should swap the pointer not try to create temporary objects and swap them.
Should be like that (there might be other mistake later)
void pswap (node *&pa, node *&pb)
{
node* temp = pa;
pa = pb;
pb = temp;
return;
}
A very simple and O(n) solution using two pointers:
start = head of the doubly LL
struct node *temp, *s;
s = start;
while(s != NULL){
temp = s->prev;
s->prev = s->next;
s->next = temp;
s = s->prev;
}
//if list has more than one node
if(current != NULL){
start = temp->prev;
}
My code for reversing doubly linked list,
Node* Reverse(Node* head)
{
// Complete this function
// Do not write the main method.
if(head != NULL) {
Node* curr = head;
Node* lastsetNode = curr;
while(curr != NULL) {
Node* frwdNode = curr->next;
Node* prevNode = curr->prev;
if(curr==head) {
curr->next = NULL;
curr->prev = frwdNode;
lastsetNode = curr;
}
else {
curr->next = lastsetNode;
curr->prev = frwdNode;
lastsetNode = curr;
}
curr = frwdNode;
}
head = lastsetNode;
}
return head;
}
I thought I'd add a recursive solution here.
node* reverse_and_get_new_head(node* head) {
if (head == nullptr) { return nullptr; }
// This can be avoided by ensuring the initial,
// outer call is with a non-empty list
std::swap(head->prev, head->next);
if (head->prev == nullptr) { return head; }
return reverse_and_get_new_head(head->prev);
}
void reverse() {
start_ptr = reverse_and_get_new_head(start_ptr);
}