leetcode day1
leetcode day1
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1!=null && list2!=null){
if(list1.val<list2.val){
list1.next=mergeTwoLists(list1.next,list2);
return list1;
}
else{
list2.next =mergeTwoLists(list1,list2.next);
return list2;
}
}
if(list1==null)
return list2;
else
return list1;
}
}
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode currNode =head;
while(currNode!= null && currNode.next!=null){
if(currNode.val==currNode.next.val){
currNode.next =currNode.next.next;
}
else{
currNode =currNode.next;
}
}
return head;
}
}
//Valid Palindrome
class Solution {
public boolean isPalindrome(String s) {
if(s.isEmpty()){
return true;
}
int start=0;
int last=s.length()-1;
while(start<=last){
char currFirst=s.charAt(start);
char currLast=s.charAt(last);
if(!Character.isLetterOrDigit(currFirst)){
start++;
}
else if(!Character.isLetterOrDigit(currLast)){
last--;
}
else{
if(Character.toLowerCase(currFirst) != Character.toLowerCase
(currLast)){
return false;
}
start++;
last--;
}
}
return true;
}
}
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head.next == null){
return null;
}
int size=0;
ListNode temp =head;
while(temp != null ){
temp=temp.next;
size++;
}
//removing Sizeth node from list i.e head
if(n == size){
return head.next;
}
//find previous node
int pstfind = size -n; //position to find
ListNode prev = head; //previous node
while(currp != pstfind){
prev =prev.next;
currp++;
}
prev.next =prev.next.next;
return head;
}
}
//valid parenthesis:
import java.util.*;
class Solution {
public boolean isValid(String s) {
Stack<Character> stack= new Stack<>();
for(int i=0 ; i<s.length();i++){
char ch =s.charAt(i);
if(stack.isEmpty()){
return true;
}
else{
return false;
}
}
//Missing Number
class Solution {
public int missingNumber(int[]nums) {
//Step1: Find the length of array.
int n = nums.length;
return allXOR;
}
}