Skip to content

Instantly share code, notes, and snippets.

@mding5692
Created September 27, 2016 03:57
Show Gist options
  • Save mding5692/da317d56e14b73a860d0550ecb26ede3 to your computer and use it in GitHub Desktop.
Save mding5692/da317d56e14b73a860d0550ecb26ede3 to your computer and use it in GitHub Desktop.
Western Tech Interview Prep Session #2 Answers
public ListNode reverseBetween(ListNode head, int m, int n) {
if(m==n) {
return head;
}
ListNode curr = head;
ListNode tempM = null;
ListNode tempAfterN = null;
ListNode tempBeforeM = null;
int nodeCount = 1 ;
while (curr!=null && nodeCount<=n){
if (nodeCount == m-1){
tempBeforeM = curr;
}
if (nodeCount == m) {
tempM = curr;
}
if (nodeCount == n) {
tempAfterN = curr.next;
curr.next = null;
}
++nodeCount;
curr = curr.next;
}
if (tempM.next == null) {
return head;
}
ListNode newTemp = tempM;
ListNode nextNode = newTemp.next;
newTemp.next = tempAfterN;
while (newTemp!=null && nextNode!=null){
ListNode tempNode = nextNode.next;
nextNode.next = newTemp;
newTemp=nextNode;
nextNode=tempNode;
}
if (tempBeforeM !=null ) {
tempBeforeM.next = newTemp;
} else {
return newTemp;
}
return head;
}
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode curr = head;
ListNode nextNode = head.next;
head.next = null;
while(curr!=null&& nextNode!=null){
ListNode temp = nextNode.next;
nextNode.next = curr;
curr = nextNode;
nextNode = temp;
}
return curr;
}
public boolean isValid(String s) {
HashMap<Character, Character> pareMap = new HashMap<Character, Character>();
pareMap.put('(', ')');
pareMap.put('[', ']');
pareMap.put('{', '}');
Stack<Character> charStack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char currChar = s.charAt(i);
if (pareMap.containsKey(currChar)) {
charStack.push(currChar);
} else if (pareMap.containsValue(currChar)) {
if (!charStack.empty() && pareMap.get(charStack.peek()) == currChar) {
charStack.pop();
} else {
return false;
}
}
}
return charStack.empty();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment