C++逆置链表的元素,头插入法

分析:
有一条链,按照一般思路,那就直接将最后一个元素的值和第一个元素的值对调就可以了。这个方法适合于数组。例如:颠倒数组。但是在链表操作的过程中我们发现我们并不能直接找到链表的尾部,如果要找,需要一次次遍历,这样,逆置一条链表将花费巨大的时间(O(n^2))。
不过,我们可以考虑将链表的每个节点拆下来,然后用头插入的方法重新连接,这样就比较高效了。

#include<iostream>
using namespace std;
struct node {
	int data;
	node* next;
};
//循环创建带有表头的链表: 
node* create(int n) {
	node* head, * tail, * p;
	head = tail = new node;
	head->data = 0;
	while (n--) {
		p = new node;
		cin >> p->data;
		p->next = NULL;
		tail->next = p;
		tail = p;
	}
	return head;
}
//逆置带头结点的链表元素,但是原来的头结点仍然保持在最前面 
node* Inversion(node*head) {
	node*p,*q;
	p=q=(head->next)->next;
	node *head1=head->next;
	head1->next=0;
	while(p){
		q=q->next;//为的是不让节点的数据走丢
		p->next=head1;
		head1=p; 
		p=q;
	}
	head->next=head1;
	return head;
}

int main() {

	int n = 3;
	node* p;
	p = create(3);
	p =Inversion(p) ;
	p = p->next;//跳过表头指针 
	while (p) {
		cout << p->data << " ";
		p = p->next;
	}
	return 0;
}

运行结果:
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值