Linked List - Solution To Assignment 02 - (PW Skills (Decode)
Linked List - Solution To Assignment 02 - (PW Skills (Decode)
Linked List - Solution To Assignment 02 - (PW Skills (Decode)
You are given the head of a linked list. Delete the middle node, and return the head of the
modified linked list. [Leetcode 2095]
The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based
indexing, where ⌊x⌋ denotes the largest integer less than or equal to x .
For n = 1 , 2 , 3 , 4 , and 5 , the middle nodes are 0 , 1 , 1 , 2 , and 2 , respectively.
Example 1:
1
Example 3:
class Solution {
public:
ListNode* deleteMiddle(ListNode* head) {
if(!head or !head->next)return NULL;
while(curr != slow){
prev = curr;
curr = curr->next;
}
prev->next = curr->next;
return head;
}
You are given two linked lists: list1 and list2 of sizes n and m respectively.
Remove list1 's nodes from the ath node to the bth node, and put list2 in their place.
[Leetcode 1669]
The blue edges and nodes in the following figure indicate the result:
2
Build the result list and return its head.
Example 1:
3
class Solution {
public:
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
ListNode *curr = list1;
a--;
while(a--){
curr = curr->next;
}
b++;
ListNode *curr2 = list1;
while(b--){
curr2 = curr2->next;
}
while(temp->next)temp = temp->next;
temp->next = curr2;
curr->next = list2;
return list1;
}
4
class Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
ListNode *temp = head;
k--;
while(k--)temp = temp->next;
ListNode *p1 = temp->next , *p2 = head;
while(p1){
p1 = p1->next;
p2 = p2->next;
}
swap(temp->val , p2->val);
return head;
}
};
Given the head of a linked list and an integer val , remove all the nodes of the linked list that has
Node.val == val , and return the new head.
Example 1:
5
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *curr = head;
head = curr;
while(curr){
if(curr->next and curr->next->val == val)
curr->next = curr->next->next;
else curr = curr->next;
}
return head;
}
};
Solution :
#include<bits/stdc++.h>
class node{
public :
int data;
node *next;
node(int n){
data = n;
next = NULL;
}
};
class linkedlist{
public:
node *head,*tail;
linkedlist(){
head = NULL;
tail = NULL;
}
void display(){
6
while(temp){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
else {
temp->next = head;
head = temp;
}
idx--;
while(idx--){
temp = temp->next;
}
temp->next->next = head->next;
}
int findLength(){
node *fast = head->next;
node *slow = head;
int fl = 0;
while(fast and fast->next){
if(fast == slow){
fl = 1;
break;
}
fast = fast->next->next;
slow = slow->next;
}
if(fl == 0)return 0;
int cnt = 1;
slow = slow->next;
7
while(slow != fast){
cnt++;
slow = slow->next;
}
return cnt;
}
};
int main(){
linkedlist ll;
ll.addFirst(1);
ll.addFirst(2);
ll.addFirst(3);
ll.addFirst(4);
ll.addFirst(5);
ll.addFirst(6);
ll.addCycle(4);
cout<<ll.findLength()<<endl;