数据结构(链表逆序)

逆序一个链表常用方法有以下几种

  • 就地逆置
  • 头插法

先初始化一个链表

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL){}
};

ListNode a(10);
ListNode b(20);
ListNode c(30);
ListNode d(40);
ListNode e(50);

a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;

ListNode *head = &a;

使用循环逆置链表(常规)【也叫 就地逆置法】

int main()
{
	// 打印旧的节点
    while(head)
    {
        cout << head->val << " " << head->next << endl ;
        head = head->next;
    }

	head = &a;							// 重置到头结点
	
	// 开始逆序
    ListNode *next = nullptr;
    ListNode *new_head = nullptr;
    
	// for(int i = 0; i < 5; ++i)  		// 需要知道有几个节点
    while(head)
    {
        next = head->next;				// 备份head 得 next的节点
        head->next = new_head;			// 断开当前节点,并 和 已经逆序的链接, 形成新的 链表
        new_head = head;				// 更新 新的链表
        head = next;					// head 获取剩余 节点
    }

	head = new_head;

	// 打印逆序后的节点
    while(head)
    {
        cout << head->val << " " << head->next << endl ;
        head = head->next;
    }

	return 0;
}

头插法

// 打印旧的节点
while(head)
{
    cout << head->val << " " << head->next << endl ;
    head = head->next;
}
head = &a;

// 开始逆序
ListNode *next = nullptr;
ListNode tmp_head(0);
while(head)
{
    next = head->next;
    head->next = tmp_head.next;
    tmp_head.next = head;
    head = next;
}

head = tmp_head.next;
while(head)
{
    cout << head->val << " " << head->next << endl ;
    head = head->next;
}

两种方法的比较:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值