第一
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.Follow up:
Can you solve it without using extra space?
大意:判断链表是否相交,并且返回第一个相交的节点。快慢指针的应用
**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null)
return null;
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){ ##当快指针和慢指针相遇时候,确定有环
while(head != slow){ ##头指针前进和环内指针第一次相遇时,为相交节点
head = head.next;
slow = slow.next;
}
return head;
}
}
return null;
}
二
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space? 同上
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL)
return NULL;
ListNode *fast = head;
ListNode *slow = head;
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
return true;
}
return false;
}
};
三判断链表是否是回文结构
思路是将前半段链表压入栈中。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
int length = get_List_length(A);
stack<int> st;
ListNode* p=A;
for(int i = 0; i < length /2 ; i++){
st.push(p->val);
p = p->next;
}
if(length %2 == 1)
p = p->next;
while( p != NULL){
if (p->val != st.top())
return false;
p = p->next;
st.pop();
}
return true;
}
int get_List_length(ListNode *A){
int count = 0;
if(A == NULL)
return 0;
while(A != NULL){
count++;
A = A->next;
}
return count;
}
};
四:
There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int i=0, j=0, median = m+n;
double prev=0, last=0;
if(median<2){
if(m == 0 && n == 0)
return 0;
if(m == 1)
return A[0];
else
return B[0];
}
while( (i+j) <= (median/2)){
prev = last;
if(i >= m){
last=B[j];
j++;
}else if(j >= n){
last = A[i];
i++;
}else if(A[i]<B[j]){
last = A[i];
i++;
}else{
last = B[j];
j++;
}
}
if((median & 1) == 0)
return (prev + last) /2;
else
return last;
}
};