Segregate even and odd nodes in a Singly Linked List - singly-linked-list

I am trying to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers same.
Below code works:
void segregateEvenOdd()
{
if(head==null) return;
Node temp=head,evenStart=null,evenEnd=null,oddStart=null,oddEnd=null;
while(temp!=null){
if(temp.data%2==0){
if(evenStart==null){
evenStart=temp;
//evenStart.next=null;
evenEnd=evenStart;
}
else{
evenEnd.next=temp;
evenEnd=evenEnd.next;
// evenEnd.next=null;
}
}
else{
if(oddStart==null){
oddStart=temp;
//oddStart.next=null;
oddEnd=oddStart;
}
else{
oddEnd.next=temp;
oddEnd=oddEnd.next;
//oddEnd.next=null;
}
}
temp=temp.next;
}
if(oddStart==null || evenStart==null) return;
evenEnd.next=oddStart;
oddEnd.next=null;
head=evenStart;
}
But when I uncomment the commented code, it doesn't work.
I am not able to understand this behavior.
Can someone explain?

In your code, evenStart, evenEnd, oddStart, oddEnd are just references which at starting are pointing to null but when it encounters first element(suppose Odd), then following code will run
if(oddStart==null){
oddStart=temp;
oddStart.next=null;
oddEnd=oddStart;
}
Here, in second line oddStart.next=null, it will not only change the next of oddStart but will also change the next of temp too. Due to which, if you uncomment everything your code will run the loop only once(because in first time temp next node will point to null).
Same case applies to all comments. You can print temp.data in loop to verify above fact.

Related

Removing duplicates from a sorted list (New Approach)

This is my program for removing duplicates from a sorted linked list. I am traversing from the head node of the linked list and using temp1 variable, I am checking whether there are any duplicates of the same value. If we find a data which is different from the current node, then we link that to current node and make it current node and repeat the process.
Here is the question:-
https://leetcode.com/problems/remove-duplicates-from-sorted-list/
ListNode* deleteDuplicates(ListNode* head) {
ListNode *curr=head,*temp1,*forw;
while(curr!=NULL)
{
//temp1 checks for next distinct element
temp1=curr->next;
while(temp1!=NULL)
{
//checking if the value at temp1 is distinct from current
if(temp1->val!=curr->val)
{
forw=temp1; //stored the distinct value in forw for reference to curr
break;
}
temp1=temp1->next;
}
curr->next=forw; // linked the distinct value to current
curr=curr->next;
}
return head;
}
But, the program is giving TLE(Time Limit Excedeed) Error.I have dry runned the code and it's working fine for me. I think i am missing some edge. Any help will be greatly appreciated?
You have UB for list of one element, as forw is then used uninitialized.
(that UB should probably do, in your case, infinite loop, so TLE).

deleting a node anywhere in a linked list

I know how to remove a node from the front of a singly linked list, but I have no idea how to remove one from any arbitrary location.
In my specific problem, I continue to pass an integer value x into each node in the linked list. I can add and delete, but there is a function I need to write where if I've identified two x's that are the same, I delete the other instance.
I can give examples of my code if anyone needs examples of what I've done so far. Thanks for any and all responses
Also, I'm working with a singly linked list.
this is a disadvantage that singly linked list has. It requires iteration to perform deletion since you can not find the previous element of an arbitrary element. What you can find is its next element. You have to iterate from the head of the lists to find its previous element.
Hope this helps.
Because each node only has a link to the subsequent node, you would have to iterate over the entire list to obtain the previous element, then link the previous with the next node. (next, as in the one after that you wish to remove)
What I was doing, when I was looking into lists, and what not is: when iterating through list, I kept the pointer to the previous element in a separate variable, and if I decided that I needed to delete current element, I already had the pointer to the previous element at hand.
So, pseudo-code wise (to better illustrate it), it would be something like this:
prevValue = NULL
for curValue = root; curValue != NULL; curValue = curValue->Next
LOOP
IF *need to delete curValue*
THEN
IF prevValue == NULL
THEN
root = curValue->Next
delete curValue
curValue = root
ELSE
prevValue->Next = curValue->Next
delete curValue
curValue = prevValue
END IF
END IF
prevValue = curValue
END LOOP
noderemove(nodehead,int d){
if(head==NULL)
cout<<"empty linked list\n";
else {
node*curr=head,*pre=NULL;
while (curr!=NULL && curr->data !=d)
{
pre=curr;
curr=curr->next;
}
if(curr==NULL)
cout<<"Mahloch this number not found\n";
else {
if(pre==NULL)
head=curr->next;
else
pre->next=curr->next;
curr->next=NULL;
delete(curr); }
}return head;
}

Program crashes when opening and processing input files

I'm currently working on a program, and I'm running into a small issue. It's reading data from a text file, and when the numbers are in ascending order, it runs fine, but when I have numbers in a random order, it crashes. I've debugged it and traced it to this if statement, but I can't figure out what the heck I did wrong.
if(tempNode != NULL)
{
struct doublyLinkNode* temp = new doublyLinkNode;
temp->nextNode = tempNode;
temp->previousNode = tempNode->previousNode;
temp->nodeValue = noToInsert;
tempNode->previousNode->nextNode = temp;
tempNode->previousNode= temp;
list->count++;
return true;
} // end if
The list building crashes when a new number to be added precedes the current top of the list. I think the pointer is attempting to write to an invalid pointer.
Your error is to be expected. You want to insert nodes before the current one (tempNode),
and you´re using tempNode->previousNode in the code.
If tempNode happens to be the first node, what´s tempNode->previousNode? Right, NULL
(unless you have a circular list, but then you wouldn´t have this problem). That means
tempNode->previousNode->nextNode = temp; will crash.
As solution to this part, just make an if:
if(tempNode->previousNode != NULL) tempNode->previousNode->nextNode = temp;
(assuming that everything is initialized properly). Depending on how you implemented the list, you may need to change the information what the first node is, too.

deleting an item in cicular linked list

My program is supposed to do 3 operations:
Insert
Delete
Show on a circular linked list.
My problem is in the delete function. here is the code:
void c_list::del()
{
int num;
if(isempty())
cout<<"List is Empty!"<<endl;
else
{
node *temp1=first;
node *temp2=NULL;
cout<<"Enter the number that u want to DELETE:"<<endl;
cin>>num;
while(temp1->next!=first && temp1->info != num)
{
temp2=temp1;
temp1=temp1->next;
}
if(num != temp1->info )
cout<<"your number was not found in the list"<<endl;
else
{
if(temp2!=NULL)
{
temp2->next=temp1->next;
cout<<temp1->info<<" was deleted"<<endl;
}
else
{
first=temp1->next;
cout<<temp1->info<<"was deleted"<<endl;
}
}
}
system("pause");
}
Delete function is working in this way: user enters a number, the program searches that number & when it founds the number, removes it from the list.
Now the problem is that, when the user enters a number that does not exist in the list, the "App crash window" appears(I mean this window:Program is not responding), while I have a provided an error message for this case("your number was not found in the list")!!
Can u tell me what the problem is?
Your insert routine is not creating a circular list. When the list is empty and the initial item is inserted first == NULL. In this case your code leaves the list in a non-circular state. Because:
newitem->next=first;
if(first==NULL)
first=newitem;
At this point first->next == NULL, which should never be the case in a circular list. Your search code fails whenever the item to be found does not exist in the list. This is because it never cycles back around to the first node, since the list is not circular.
I think in your while loop you are reaching to the end of list and
after below line temp1 gets NULL.
temp1=temp1->next;
Then you are trying to read info attribute from null pointer and this causes error.
if(num != temp1->info )
I know you said it is circular list but i am not sure it is implemented correctly or not. My suggestion is just try to print temp1->info after while loop to be sure that correctness of list and your implementation.
Happen that, if you insert a number that is not in list, you have a loop in the first while.
So:
node* temp1 = first;
node* temp2 = 0;
while(temp1->next!=first && !temp2) {
if(temp1->info == num) {
/* save pointer and exit from while */
temp2 = temp1;
} else {
temp1 = temp1->next;
}
}
Then your code produce garbage because you never call a delete.
Most likely the problem is on the insert method, where maybe, you don't assign correcly pointers.
And then, why system("pause"); ? Take a look here.

Insertion in ordered linked list

I'm trying to insert a node in a linked list so that the nodes are ordered in ascending mode by de idx parameter.
void add(int i){
if(find(i)==NULL){ //if node does not exist
node *m=new node;
m->idx=i;
m->values=NULL;
m->next=NULL;
if(list==NULL){ //if list is empty
list=m;
return;
}
if(i < list->idx){ //if the new node comes before the head node
m->next=list;
list=m;
return;
}
//if the new node is bigger than the maximum node index in the list
if(i > maxIdx(list)){
node *last=lastNode(list);
last->next=m;
}
//else normal insertion
node *prev=list;
node *curr=list->next;
while(curr!=NULL){
if( i < curr->idx){
m->next=curr;
prev->next=m;
return;
}
prev=curr;
curr=curr->next;
}
}
}
Edited with correct implementation, the fourth if was missing before.
It seems correct to me as well, as far as segfault is concerned. However, you don't consider the case when i is greater than the largest number in the list. In this case, you should insert i at the end of the list. So try fixing this bug first, maybe it will fix the segfault as well (which is coming from elsewhere, maybe from your find() implementation).
Now it seems that is the answer (as your comment on my comment confirms it).