Linked List Questions
Table of contents
Hello Community, So today I solved some questions on LinkedList.
Hello Community, So today I solved some questions on LinkedList.
1. Remove Duplicates from Sorted LinkedList
public ListNode deleteDuplicates(ListNode node) {
if(node == null){
return node;
}
ListNode head = node;
while(node.next != null){
if(node.val == node.next.val){
node.next = node.next.next;
} else {
node = node.next;
}
}
return head;
}
2. Merge Two Sorted LinkedLists.
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummyHead = new ListNode();
ListNode tail = dummyHead;
while(list1 != null && list2 != null){
if(list1.val <= list2.val){
tail.next = list1;
list1 = list1.next;
tail = tail.next;
} else {
tail.next = list2;
list2 = list2.next;
tail = tail.next;
}
}
while(list1 != null){
tail.next = list1;
list1 = list1.next;
tail = tail.next;
}
while(list2 != null){
tail.next = list2;
list2 = list2.next;
tail = tail.next;
}
return dummyHead.next;
}
3. Detect the LinkedList Cycle
public boolean hasCycle(ListNode head) {
if(head == null){
return false;
}
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null ){
fast = fast.next.next;
slow = slow.next;
if(fast==slow){
return true;
}
}
return false;
}
4. Detect where the LinkedList cycle is starting.
public int lengthOfCycle(ListNode head){
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null ){
fast = fast.next.next;
slow = slow.next;
if(fast==slow){
ListNode temp = slow;
int cnt = 0;
do{
temp = temp.next;
cnt++;
} while (temp != slow);
return cnt;
}
}
return 0;
}
public ListNode detectCycle(ListNode head) {
int length = 0;
ListNode fast = head;
ListNode slow = head;
while(fast!= null && fast.next != null ){
fast = fast.next.next;
slow = slow.next;
if(fast==slow){
length = lengthOfCycle(head);
break;
}
}
if(length == 0) return null;
ListNode f = head;
ListNode s = head;
while(length > 0){
s = s.next;
length--;
}
while(f != s){
f=f.next;
s=s.next;
}
return s;
}
5. Happy Number
public boolean isHappy(int n) {
int slow = n;
int fast = n;
do{
slow = calculate(slow);
fast = calculate(calculate(fast));
} while(slow != fast);
if(slow == 1) return true;
return false;
}
public int calculate(int n){
int ans = 0;
while(n>0){
int rem = n%10;
ans += rem*rem;
n = n/10;
}
return ans;
}
6. Find middle of LinkedList.
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
Today it's my first blog on HshNode..
I will try to post a blog consistently on Hashnode.
Now I will try to upload all my sharings and learnings in DSA and development whatever I will do.I will invite folks from the community to come up along with me and let us post our daily learnings with everyone.