倒置数组:
算法很简单,两个变量,左边的一直加,右边的一直减,两者相同后停止扫描.
/*
* 1.cpp
*
* Created on: 2015-11-11
* Author: sunyuan
* reserve array
*/
//
#include<iostream>
using namespace std;
void reverve(int[],int);
void output(int[],int);
int main(){
int array[]={1,2,3,5,6,4,8};
reverve(array,7);
output(array,7);
return 0;
}
void reverve(int array[],int length){
int left=0;
int right=length-1;
while(left<right){
int temp=array[left];
array[left]=array[right];
array[right]=temp;
left++;
right--;
}
}
void output(int array[],int length){
int n=0;
while(n<length){
cout<<array[n]<<endl;
n++;
}
}
倒置链表:
倒置链表可以采用递归的思想,假如只有两个节点,假设最后一个节点为rear,头节点为head,我只要把rear->next=head;head->next=NULL;每两两元素都是这样,可以采用递归的方法。
/*
* 3.cpp
*
* Created on: 2015-11-12
* Author: sunyuan
* reverse linklist
*/
#include<iostream>
using namespace std;
struct node{
int playload;
node* next;
};
//reverse linklist
node* reverseLinkList(node* head){
if(head == NULL || head->next == NULL){
return head;
}
node* next=head->next;
node* new_node=reverseLinkList(next);
next->next=head;
head->next=NULL;
return new_node;
}
//output list
void output(node* head){
while(head!=NULL){
cout<<head->playload<<endl;
head=head->next;
}
}
int main(){
node* head=new node;
head->playload=0;
node* first=head;
// insert 10 items
for(int i=1;i<10;i++){
node* new_node=new node;
new_node->playload=i*10;
head->next=new_node;
head=new_node;
}
output(first);
output(reverseLinkList(first));
return 0;
}
数组和链表都是数据结构的基本,核心,所以知识点一定要牢固。