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

本文探讨了如何使用C++实现倒置数组的算法,通过两个指针,一个从左向右移动,一个从右向左移动,当两者相遇时结束扫描。此外,还介绍了倒置链表的方法,提出可以利用递归策略来完成链表节点的反转。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

倒置数组:

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

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



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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值