File tree Expand file tree Collapse file tree 2 files changed +69
-0
lines changed
160_IntersectionOfTwoLinkedLists Expand file tree Collapse file tree 2 files changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ class MinStack {
2
+ public:
3
+ MinStack () {
4
+ }
5
+
6
+ void push (int x) {
7
+ m_stack.push (x);
8
+ if (m_minStack.empty () || m_minStack.top () >= x) m_minStack.push (x);
9
+ }
10
+
11
+ void pop () {
12
+ int t = m_stack.top ();
13
+ m_stack.pop ();
14
+ if (t == m_minStack.top ()) m_minStack.pop ();
15
+ }
16
+
17
+ int top () {
18
+ return m_stack.top ();
19
+ }
20
+
21
+ int getMin () {
22
+ return m_minStack.top ();
23
+ }
24
+
25
+ private:
26
+ stack<int > m_stack;
27
+ stack<int > m_minStack;
28
+ };
Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Definition for singly-linked list.
3
+ * struct ListNode {
4
+ * int val;
5
+ * ListNode *next;
6
+ * ListNode(int x) : val(x), next(NULL) {}
7
+ * };
8
+ */
9
+ class Solution {
10
+ public:
11
+ ListNode *getIntersectionNode (ListNode *headA, ListNode *headB) {
12
+ auto getLenth = [](ListNode *head) {
13
+ int len = 0 ;
14
+ ListNode *p = head;
15
+ while (p) {
16
+ ++len;
17
+ p = p->next ;
18
+ }
19
+ return len;
20
+ };
21
+ int lenA = getLenth (headA);
22
+ int lenB = getLenth (headB);
23
+ ListNode *a = headA;
24
+ ListNode *b = headB;
25
+ int delta = abs (lenA-lenB);
26
+ if (lenA>lenB) {
27
+ while (delta--) {
28
+ a = a->next ;
29
+ }
30
+ } else {
31
+ while (delta--) {
32
+ b = b->next ;
33
+ }
34
+ }
35
+ while (a && a != b) {
36
+ a = a->next ;
37
+ b = b->next ;
38
+ }
39
+ return a;
40
+ }
41
+ };
You can’t perform that action at this time.
0 commit comments