加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

倒置数组和链表(C++)

发布时间:2020-12-13 22:12:33 所属栏目:百科 来源:网络整理
导读:倒置数组: 算法很简单,两个变量,左边的一直加,右边的一直减,两者相同后停止扫描. /* * 1.cpp * * Created on: 2015-11-11 * Author: sunyuan * reserve array *///#includeiostreamusing namespace std;void reverve(int[],int);void output(int[],int);int

倒置数组:

算法很简单,两个变量,左边的一直加,右边的一直减,两者相同后停止扫描.

/*
 * 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;
}


数组和链表都是数据结构的基本,核心,所以知识点一定要牢固。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读