倒置数组:
算法很简单,两个变量,左边的一直加,右边的一直减,两者相同后停止扫描.
/* * 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; }数组和链表都是数据结构的基本,核心,所以知识点一定要牢固。
原文地址:https://www.jb51.cc/javaschema/284328.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。