This code add Two sum integer using linkedList.
I have added to the struct ListNode a new constructor in order to give him as input two vectore A and B.
ListNode(vector<int> array)
{
vector<int>::iterator itr = array.begin();
ListNode *t = nullptr;
for (; itr < array.end(); itr++) {
t->val = *itr;
t = t->next;
}
}
This is a strange overflow ??
#include <iostream>
#include <vector>
using namespace std;
/*
Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
ListNode(vector<int> array)
{
vector<int>::iterator itr = array.begin();
ListNode *t = nullptr;
for (; itr < array.end(); itr++) {
t->val = *itr;
t = t->next;
}
}
};
class Solution {
public:
Solution(){};
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *p = l1;
ListNode *q = l2;
ListNode *dummyHead = new ListNode(0);
ListNode *current = dummyHead;
int carry = 0;
while (p != NULL || q != NULL) {
int x = (p != NULL) ? p->val : 0;
int y = (q != NULL) ? q->val : 0;
int sum = carry + x + y;
carry = sum / 10;
current->next = new ListNode(sum % 10);
current = current -> next;
if (p != NULL) {
p = p -> next;
}
if (q != NULL) {
q = q -> next;
}
}
if (carry > 0) {
current -> next = new ListNode(carry);
}
return dummyHead->next;
}
};
int main(int argc, const char * argv[]) {
Solution *sol = nullptr;
vector<int> A = {2,4,3};
vector<int> B = {5,6,4};
ListNode *list1= new ListNode(A);
ListNode *list2= new ListNode(B);
sol->addTwoNumbers(list1,list2);
return 0;
}
Use case for test:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Your ListNode constructor is not creating a new ListNode for t to point at before you access t->val. It is also not even attempting to initialize the members of this.
Try something more like this instead:
struct ListNode {
int val = 0;
ListNode *next = nullptr;
ListNode(int x = 0, ListNode *next = nullptr) : val(x), next(next) {}
ListNode(const vector<int> &array)
{
if (!array.empty()) {
auto itr = array.begin();
val = *itr++;
ListNode **t = &next;
while (itr != array.end()) {
*t = new ListNode(*itr++);
t = &((*t)->next);
}
}
}
};
That being said, having such a constructor in ListNode really makes no sense. A list node should only care about its own data, not about the data of the nodes around it. This kind of list construction really belongs in a separate List class that wraps a chain of ListNodes, eg:
#include <iostream>
#include <vector>
#include <utility>
/*
Definition for singly-linked list.
*/
struct ListNode {
int val = 0;
ListNode *next = nullptr;
ListNode(int x = 0, ListNode *next = nullptr) : val(x), next(next) {}
};
class List {
private:
ListNode *head = nullptr;
public:
List() = default;
List(const vector<int> &vec)
{
ListNode **t = &head;
for (int val : vec) {
*t = new ListNode(val);
t = &((*t)->next);
}
}
List addNumber(const List &l) const {
ListNode *p = head;
ListNode *q = l.head;
List dummyList;
ListNode** current = &(dummyList.head);
int carry = 0;
while (p || q) {
int x = (p) ? p->val : 0;
int y = (q) ? q->val : 0;
int sum = carry + x + y;
carry = sum / 10;
*current = new ListNode(sum % 10);
current = &((*current)->next);
if (p) {
p = p->next;
}
if (q) {
q = q->next;
}
}
if (carry > 0) {
*current = new ListNode(carry);
}
return dummyList;
}
// what follows is stuff needed for compliance with the "Rule of 3/5/0":
// https://en.cppreference.com/w/cpp/language/rule_of_three
List(const List &list)
{
ListNode **t = &head;
for(ListNode *n = list.head; n; n = n->next) {
*t = new ListNode(n->val);
t = &((*t)->next);
}
}
List(List &&list)
{
std::swap(head, list.head);
}
~List()
{
ListNode *n;
for (ListNode *t = head; t; t = n) {
n = t->next;
delete t;
}
}
List& operator=(List rhs) {
List temp(std::move(rhs));
std::swap(head, temp.head);
return *this;
}
};
class Solution {
public:
List addTwoNumbers(const List &l1, const List &l2) {
return l1.addNumber(l2);
}
};
int main(int argc, const char * argv[]) {
Solution sol;
vector<int> A = {2,4,3};
vector<int> B = {5,6,4};
List list1(A);
List list2(B);
List result = sol.addTwoNumbers(list1, list2);
return 0;
}
You are dereferencing a null pointer that's why you get the memory error. You have to initialize it and allocate memory. Here you initialize ListNode *t = nullptr;. So t is referencing as NULL pointer. Next, you here dereferencing t->val = *itr; but t is pointing to NULL.
Try something like this for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
};
Then your main task is to create a link list from a vector, for this you can use a class that holds the vector link list. And another requirement is to add to the vector link list. So we can create a vector link list in reverse order. And for this, you can use this code snippet.
class VectorList {
public:
ListNode *root;
VectorList() : root(nullptr){}
VectorList(vector<int> &array){
root = new ListNode();
ListNode *curr;
curr = root;
int _size = array.size();
for(int i = _size - 1; i >= 0; i--){
ListNode *t = new ListNode(array[i]);
curr->next = t;
curr = curr->next;
}
root = root->next;
}
};
So now we can create two vector lists and then add the vector lists and print the desired answer. And for this, you can use this code snippet.
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* curr, *root = NULL;
int carry = 0;
while(l1 || l2){
if(l1 != NULL && l2 != NULL){
ListNode* t = new ListNode;
t->val = (l1->val + l2->val + carry) % 10;
t->next = NULL;
carry = (l1->val + l2->val + carry) / 10;
if(root == NULL){
curr = root = t;
}
else{
curr->next = t;
curr = curr->next;
}
l1 = l1->next;
l2 = l2->next;
}
else if(l1 == NULL){
ListNode* t = new ListNode;
t->val = (l2->val + carry) % 10;
t->next = NULL;
carry = (l2->val + carry) / 10;
if(root == NULL){
curr = root = t;
}
else{
curr->next = t;
curr = curr->next;
}
l2 = l2->next;
}
else if(l2 == NULL){
ListNode* t = new ListNode;
t->val = (l1->val + carry) % 10;
t->next = NULL;
carry = (l1->val + carry) / 10;
if(root == NULL){
curr = root = t;
}
else{
curr->next = t;
curr = curr->next;
}
l1 = l1->next;
}
}
if(carry){
ListNode* t = new ListNode;
t->val = carry;
t->next = NULL;
curr->next = t;
}
return root;
}
void print(ListNode *root){
ListNode *curr = root;
while(curr){
cout << curr->val << " ";
curr = curr->next;
}
cout << endl;
}
};
So overall, here is the main code with the desired output.
#include <iostream>
#include <vector>
using namespace std;
/*
Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
};
class VectorList {
public:
ListNode *root;
VectorList() : root(nullptr){}
VectorList(vector<int> &array){
root = new ListNode();
ListNode *curr;
curr = root;
int _size = array.size();
for(int i = _size - 1; i >= 0; i--){
ListNode *t = new ListNode(array[i]);
curr->next = t;
curr = curr->next;
}
root = root->next;
}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* curr, *root = NULL;
int carry = 0;
while(l1 || l2){
if(l1 != NULL && l2 != NULL){
ListNode* t = new ListNode;
t->val = (l1->val + l2->val + carry) % 10;
t->next = NULL;
carry = (l1->val + l2->val + carry) / 10;
if(root == NULL){
curr = root = t;
}
else{
curr->next = t;
curr = curr->next;
}
l1 = l1->next;
l2 = l2->next;
}
else if(l1 == NULL){
ListNode* t = new ListNode;
t->val = (l2->val + carry) % 10;
t->next = NULL;
carry = (l2->val + carry) / 10;
if(root == NULL){
curr = root = t;
}
else{
curr->next = t;
curr = curr->next;
}
l2 = l2->next;
}
else if(l2 == NULL){
ListNode* t = new ListNode;
t->val = (l1->val + carry) % 10;
t->next = NULL;
carry = (l1->val + carry) / 10;
if(root == NULL){
curr = root = t;
}
else{
curr->next = t;
curr = curr->next;
}
l1 = l1->next;
}
}
if(carry){
ListNode* t = new ListNode;
t->val = carry;
t->next = NULL;
curr->next = t;
}
return root;
}
void print(ListNode *root){
ListNode *curr = root;
while(curr){
cout << curr->val << " ";
curr = curr->next;
}
cout << endl;
}
};
int main(int argc, const char * argv[]) {
Solution *sol = nullptr;
vector<int> A = {2,4,3};
vector<int> B = {5,6,4};
VectorList list1 = VectorList(A);
VectorList list2 = VectorList(B);
ListNode *root = sol->addTwoNumbers(list1.root, list2.root);
sol->print(root);
return 0;
}
Sample Input:
l1 = [2,4,3], l2 = [5,6,4]
Sample Output:
[7 0 8]
Related
Trying to solve Odd Even Linked List question.
Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
My try:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
int n = 1;
ListNode* l = nullptr;
ListNode *u = l;
ListNode* r = r;
ListNode* ru = nullptr;
while(head){
ListNode* c = new ListNode(head->val);
if(n%2){
if(r == nullptr){
r = c;
}
else{
r->next = c;
r = r->next;
}
}
else{
if(l == nullptr){
l = c;
}
else{
l->next = c;
l = l->next;
}
}
n++;
head=head->next;
}
l->next = ru;
return u;
}
};
But getting the below error:
Line 27: Char 24: runtime error: member access within misaligned address 0x9ddfea08eb382d69 for type 'ListNode', which requires 8 byte alignment (solution.cpp)
0x9ddfea08eb382d69: note: pointer points here
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:36:24
What does the error mean and to solve it.
Link: https://leetcode.com/problems/odd-even-linked-list/
The problem is (once we fix the typo):
ListNode *l = nullptr;
ListNode *u = l;
...
return u;
u is always nullptr. One quick hack would be:
ListNode *l = nullptr;
ListNode **u = &l;
ListNode *r = nullptr;
ListNode **ru = &r;
...
l->next = *ru;
return *u;
Or you could try:
if(r == nullptr){
r = c;
ru = r; // Add this
}
...
if(l == nullptr){
l = c;
u = l; // Add this
}
Please check the code with comments marked as // CHANGE HERE
Tested here: https://godbolt.org/z/c3e5M739d
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution
{
public:
ListNode* oddEvenList(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
int n = 1;
// CHANGE HERE: set all to nullptr
ListNode* l = nullptr;
ListNode* u = nullptr;
ListNode* r = nullptr;
ListNode* ru = nullptr;
while(head){
// std::cout << head->val << " ";
ListNode* c = new ListNode(head->val);
if(n%2){
// CHANGE HERE: replace r with ru
if(ru == nullptr){
r = c;
// CHANGE HERE: set ru
ru = r;
}
else{
r->next = c;
r = r->next;
}
}
else{
// CHANGE HERE: replace l with u
if(u == nullptr){
l = c;
// CHANGE HERE: set u
u = l;
}
else{
l->next = c;
l = l->next;
}
}
n++;
head=head->next;
}
l->next = ru;
return u;
}
};
int main()
{
ListNode* node = new ListNode(1);
node->next = new ListNode(2);
node->next->next = new ListNode(3);
node->next->next->next = new ListNode(4);
node->next->next->next->next = new ListNode(5);
node->next->next->next->next->next = new ListNode(6);
Solution s;
ListNode* l = s.oddEvenList(node);
ListNode* q = l;
while (q)
{
std::cout << q->val << " ";
q = q->next;
}
}
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;
}
I wrote a code of getting a linked list with numbers, and trying to make the list as ascending series. Unfortunately the code is not complied and I don't know why.
I have tried to play with the pointers and references but I cant put my hand on what is wrong.
#include <iostream>
using namespace std;
class ListNode {
public:
ListNode(const int &info) : data(info), nextPtr(0) {}
int getData() const { return data; }
ListNode *getNext() const { return nextPtr; }
void setNext(ListNode *next) { nextPtr = next; }
private:
int data;
ListNode *nextPtr;
};
ListNode sort(ListNode &temp) {
ListNode *first = &temp;
ListNode *curr = first;
ListNode *next = curr->getNext();
ListNode *found = 0;
while (curr->getNext() != 0) {
if (curr->getData() > next->getData()) {
if (curr == first) {
first = next;
found = curr;
}
else {
curr->setNext(next->getNext());
found = next;
}
break;
}
curr = next;
next = next->getNext();
}
curr = first;
next = curr->getNext();
while (curr->getNext() != 0) {
if (curr->getData() <= found->getData() &&
found->getData() < next->getData()) {
curr->setNext(found);
found->setNext(next);
break;
}
curr = next;
next = next->getNext();
}
return *first;
}
void print(ListNode &temp) {
ListNode *curr = &temp;
while (curr != 0) {
cout << curr->getData() << " ";
curr = curr->getNext();
}
cout << endl;
}
int main1() {
ListNode a(2);
ListNode b(5);
ListNode c(8);
ListNode d(13);
ListNode e(18);
ListNode f(7);
ListNode g(21);
a.setNext(&b);
b.setNext(&c);
c.setNext(&d);
d.setNext(&e);
e.setNext(&f);
f.setNext(&g);
print(a);
print(sort(a));
return 0;
}
I have checked hundred times and do not know why this code is not compiling.
sort() should return a pointer to the node, so return first instead of *first and change the return type to ListNode*. Then change print(sort(a)) to print(*sort(a)). See it run here: http://coliru.stacked-crooked.com/a/c3e72983e83f6914
#include<iostream>
using namespace std;
class ListNode
{
public:
ListNode(const int &info) :data(info), nextPtr(0)
{
}
int getData() const
{
return data;
}
ListNode * getNext() const
{
return nextPtr;
}
void setNext(ListNode * next)
{
nextPtr = next;
}
private:
int data;
ListNode *nextPtr;
};
ListNode sort(ListNode &temp)
{
ListNode *first = &temp;
ListNode *curr = first;
ListNode *next = curr->getNext();
ListNode *found = 0;
while (curr->getNext() != 0)
{
if (curr->getData() > next->getData())
{
if (curr == first)
{
first = next;
found = curr;
}
else
{
curr->setNext(next->getNext());
found = next;
}
break;
}
curr = next;
next = next->getNext();
}
curr = first;
next = curr->getNext();
while (curr->getNext() != 0)
{
if (curr->getData() <= found->getData() && found->getData() < next->getData())
{
curr->setNext(found);
found->setNext(next);
break;
}
curr = next;
next = next->getNext();
}
return *first;
}
You are passing a temporary(rvalue) to a function which expects an lvalue
void print(const ListNode &temp)
{
const ListNode * curr = &temp;
while (curr != 0)
{
cout << curr->getData() << " ";
curr = curr->getNext();
}
cout << endl;
}
//I am expecting main() here , I think this is what you meant.
int main()
{
ListNode a(2);
ListNode b(5);
ListNode c(8);
ListNode d(13);
ListNode e(18);
ListNode f(7);
ListNode g(21);
a.setNext(&b);
b.setNext(&c);
c.setNext(&d);
d.setNext(&e);
e.setNext(&f);
f.setNext(&g);
print(a);
print(sort(a));
return 0;
}
This an implementation of doubly linked list in c++
..I try to insert elements in my linked list
so I added the numbers 2 , 2 , 2 , 4 , 8 , 7
before printing , I call quicksort function
quick sort replaces the last element ( 7 ) , with the previous element (8)
..print function results in the output : 2,2,2,4 , 7 , 7
How can this code be modified to get the correct result
Here is my code..
#include <iostream>
using namespace std ;
template <class T>
class node
{
public :
T data;
node * next;
node * previous ;
};
template <class T>
class LinkedList
{
public:
string delimeter; // optional: just for printing
node<T>* addSorted(T v)
{
insert(T) ;
_quicksort(first , last) ;
}
void swap ( T* a, T* b )
{
T t = *a;
*a = *b;
*b = t;
}
node<T>* get(T v)
{
bool found = false ;
node<T> * Curr = first ;
while (!found)
{
if (Curr-> data == v )
found = true;
else
Curr = Curr-> next;
}
return Curr ;
}
// operator overloading for printing
friend ostream& operator<<(ostream& o, LinkedList<T> & c);
LinkedList()
{
node<T> * curr = new node<T> ;
first = last = curr;
first->next = last ;
first-> previous = NULL;
}
LinkedList(T value, int initial_size) // make n elements = value
{
node<T> * tempNode ;
node<T> * curr = new node<T> ;
first = last = curr;
first->previous =NULL;
for(int i = 0 ; i < initial_size ; i++)
{
tempNode = new node<T>;
tempNode->data = value ;
tempNode->next = first;
first->previous = tempNode;
first = tempNode ;
}
}
~LinkedList()
{
node<T> * current ;
while (first != last)
{
current = first ;
first = first-> next;
delete current;
}
delete last;
}
void print()
{
_quickSort(first, last);
//bubbleSort(first) ;
node<T> * Curr = first ;
while (Curr != NULL)
{
cout << Curr-> data <<"\t";
Curr = Curr-> next;
}
cout << endl;
}
int _size() // returns No. of elements
{
int NumOfelements = 0;
node<T> * temp = first ;
while (temp != last)
{
NumOfelements++;
temp = temp->next;
}
return NumOfelements ;
}
void insert(T value )
{
node<T> * temp = first ;
node<T> * dummy ;
node<T> * n = new node<T> ;
n->data = value;
last->data = value;
last->next = n;
n->previous = last;
last = n;
return;
while (temp != nullptr)
{
dummy = temp ;
temp = temp->next;
if(temp==last)
{
return;
}
}
dummy ->next = n ;
n -> previous = dummy;
n -> next = temp ;
temp-> previous =n;
// _quickSort(first, last) ;
//bubbleSort(first) ;
}
/* Considers last element as pivot, places the pivot element at its
correct position in sorted array, and places all smaller (smaller than
pivot) to left of pivot and all greater elements to right of pivot */
node<T>* pivot_partition(node<T> *f, node<T> *l)
{
// set pivot as l element
T x = l->data;
node<T> *i = f-> previous;
for (node<T> *j = f; j != l; j = j->next)
{
if (j->data <= x)
{
if (i == NULL)
i = f ;
else
i = i-> next ;
swap(&(i->data), &(j->data));
}
}
i = (i == NULL)? f : i->next; // Similar to i++
swap(&(i->data), &(l->data));
return i;
}
/* A recursive implementation of quicksort for linked list */
void _quickSort(node<T> *first, node<T> *last )
{
if (last != NULL && first != last && first != last->next)
{
node<T> *p = pivot_partition(first, last);
_quickSort(first, p->previous);
_quickSort(p->next, last);
}
}
T mylast () // even this returns 7 not 8
{
return last->data ;
}
private:
node<T> * first ;
node<T> * last ;
};
int main (){
LinkedList <int> l(2,3) ;
l.insert(4) ;
l.insert(8) ;
l.insert(7) ;
l.print() ;
return 0 ;
}
I fixed many small issues like styling and nullptr. But the big problems were in the constructor and in insert. The constructor created one element to much and initialized it with a default value. The insert method overwrote the last element. Next time please use a tool for code style before posting it here.
#include <iostream>
using namespace std;
template <class T>
class node {
public:
T data;
node* next;
node* previous;
};
template <class T>
class LinkedList {
public:
string delimeter;
node<T>* addSorted(T v) {
insert(v);
_quicksort(first , last);
}
void swap(T* a, T* b) {
T t = *a;
*a = *b;
*b = t;
}
node<T>* get(T v) {
bool found = false;
node<T>* Curr = first;
while (!found) {
if (Curr->data == v )
found = true;
else
Curr = Curr->next;
}
return Curr;
}
friend ostream& operator<<(ostream& o, LinkedList<T>& c);
LinkedList() {
node<T>* curr = new node<T>;
first = last = curr;
first->next = last ;
first->previous = nullptr;
}
LinkedList(T value, int initial_size) {
if (initial_size <= 0) return;
node<T>* tempNode;
node<T>* curr = new node<T>;
curr->data = value;
first = last = curr;
first->previous = nullptr;
for(int i = 0; i < initial_size - 1; i++) {
tempNode = new node<T>;
tempNode->data = value;
tempNode->next = first;
first->previous = tempNode;
first = tempNode;
}
}
~LinkedList() {
node<T>* current;
while (first != last) {
current = first;
first = first->next;
delete current;
}
delete last;
}
void print() {
_quickSort(first, last);
node<T>* Curr = first;
while (Curr != nullptr) {
cout << Curr->data << "\t";
Curr = Curr->next;
}
cout << endl;
}
int _size() {
int NumOfelements = 0;
node<T>* temp = first;
while (temp != last) {
NumOfelements++;
temp = temp->next;
}
return NumOfelements;
}
void insert(T value) {
node<T>* temp = first;
node<T>* dummy;
node<T>* n = new node<T>;
n->data = value;
last->next = n;
n->previous = last;
last = n;
return;
while (temp != nullptr) {
dummy = temp;
temp = temp->next;
if (temp == last) {
return;
}
}
dummy->next = n ;
n->previous = dummy;
n->next = temp;
temp->previous = n;
}
node<T>* pivot_partition(node<T>* f, node<T>* l) {
T x = l->data;
node<T>* i = f->previous;
for (node<T>* j = f; j != l; j = j->next) {
if (j->data <= x) {
if (i == nullptr)
i = f;
else
i = i->next;
swap(&(i->data), &(j->data));
}
}
i = (i == nullptr) ? f : i->next;
swap(&(i->data), &(l->data));
return i;
}
void _quickSort(node<T>* first, node<T>* last) {
if (last != nullptr && first != last && first != last->next) {
node<T>* p = pivot_partition(first, last);
_quickSort(first, p->previous);
_quickSort(p->next, last);
}
}
T mylast() {
return last->data;
}
private:
node<T>* first;
node<T>* last;
};
int main() {
LinkedList<int> l(2,3);
l.insert(4);
l.insert(8);
l.insert(7);
l.print();
return 0;
}
I am writing a function to delete a give number from a linked list in codefights. I am passing 6 out of 7 test cases, however, the 7th is hidden so I am not able to see what it is I am doing wrong. Can anyone see what test case I am missing with this function?
// Definition for singly-linked list:
// template<typename T>
// struct ListNode {
// ListNode(const T &v) : value(v), next(nullptr) {}
// T value;
// ListNode *next;
// };
#include <stdio.h>
ListNode<int> * removeKFromList(ListNode<int> * l, int k) {
ListNode<int> *cur = l;
ListNode<int> *temp = l;
while (cur != NULL) {
if (cur->value == k) {
if (cur == l) {
ListNode<int> *del;
del = cur;
cur = cur->next;
l = l->next;
temp = temp->next;
delete del;
} else {
ListNode<int> *del = cur;
cur = cur->next;
temp->next = cur;
delete del;
}
} else {
temp = cur;
cur = cur->next;
}
}
return l;
}