#逆置
头插法
struce ListNode* reverseList(struct ListNode* head){
struct ListNode temp;
temp.next=NULL;
while(head){
struct ListNode* next=head->next;
head->next=temp.text;
temp.next=head;
head=next;
}
return temp.next;
}
struce ListNode* reverseList(struct ListNode* head){
struct ListNode p=head->next->next;
while(p){
struct Listnode q=p->next;
p=head->next;
head->next=p;
p=q;
}
return temp.next;
}
数组
int reverseArray(int[] array,int size){
for(int i=0;i<size/2-1;i++){
int a=array[i];
array[i]=array[size-i-1];
array[size-i-1]=a;
}
}
#快慢指针
找到链表倒数第k个
int findK(struct ListNode* head,k){
struct ListNode* p,q;
p=head;
int count=0;
while(p->next){
count++;
if(count<=k)p=p->next;
if(p->next==NULL)return q->data;
p=p->next;
q=q->next;
}
}
#排序
快排
int getStandard(auto& array, int i, int j) {
int key = array[i];
while (i < j) {
while (i < j && array[j] >= key) {
j--;
}
if (i < j) {
array[i] = array[j];
}
while (i < j && array[i] <= key) {
i++;
}
if (i < j) {
array[j] = array[i];
}
}
array[i] = key;
return i;
}
void QuickSort(auto& array, int low, int high) {
if (low < high) {
int standard = getStandard(array, low, high);
QuickSort(array, low, standard - 1);
QuickSort(array, standard + 1, high);
}
}
归并
// 合并(Merge)
void merge(vector<int> &vec, int start, int mid, int end) {
vector<int> temp; // 用来保存二路归并的临时结果
int i = start, j = mid + 1;
// 二路归并
while (i <= mid && j <= end) {
if (vec[i] < vec[j]) {
temp.push_back(vec[i++]);
} else {
temp.push_back(vec[j++]);
}
}
// 处理剩余的
while (i <= mid) temp.push_back(vec[i++]);
while (j <= end) temp.push_back(vec[j++]);
//重新赋值回去
for (int k = 0; k < temp.size(); k++) {
vec[start + k] = temp[k];
}
}
// mergeSort
void mergeSort(vector<int> &vec, int start, int end) {
// 递归出口
if (vec.empty() || start >= end) {
return;
}
// 二分
int mid = start + (end - start) / 2;
// 递归
mergeSort(vec, start, mid);
mergeSort(vec, mid + 1, end);
// 归并
merge(vec, start, mid, end);
}
#二分查找
int binarySearch(int[] data,int n,int x){
int low=0,high=n-1,mid=0;
while(low<=high){
mid=(low+high)/2;
if(x==data[mid]) {
return mid;
}else if(x<data[mid]){
high=mid-1;
}else{
low=mid+1;
}
}
return -1;
}
int binaryDiGuiSearch(int[] data,int low,int high,int x) {
if(low>high){
return -1;
}
int mid=(low+high)/2;
if(x==data[mid]){
return mid;
}else if(x<data[mid]){
return binaryDiGuiSearch( data,low,mid-1,x);
}else {
return binaryDiGuiSearch( data,mid+1,high,x);
}
}