实现链表逆序遍历的两种方法

一、不改变节点的位置

利用栈存储数据的特性——先进后出,将链表的节点压入栈中,再将节点出栈,实现链表的逆序遍历

    // 逆序打印链表,不改变链表的数据位置(利用栈的特性)
	public static void reversePrint(HeroNode head) {
		if (head.next == null) 
			return;
		HeroNode currentNode = head.next;
		Stack<HeroNode> stack = new Stack<HeroNode>(); // 利用栈的特性,先进后出
		while (currentNode != null) {
			stack.push(currentNode); // 入栈
			currentNode = currentNode.next;
		}
		while (stack.size() > 0) {
			System.out.println(stack.pop()); // 出栈,实现逆序打印
		}
	}

二、反转链表,改变节点的位置

思路:

  1. 新建一个头节点;
  2. 将原来链表的节点依次加入到新头节点的最前端
  3. 将原来头节点指向新的头节点。
	public static void reverseLinkedList(HeroNode head) {
		if (head.next == null || head.next.next == null) 
			return;
		HeroNode temp = head.next;
		HeroNode next = null; // 当前节点的下一个节点!!!
		HeroNode newHead = new HeroNode(0, null, null); // 新的头节点
		while (temp != null) {
			next = temp.next; // 暂时保存当前节点的下一个节点
			temp.next = newHead.next; // 将temp的下一个节点指向新链表的最前端!!!
			newHead.next = temp; // 连接到新的链表
			temp = next; // temp后移
		}
		head.next = newHead.next; // 实现链表反转
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现链表逆序输出,可以使用递归或者迭代的方式。以下是分别使用这两种方法的示例代码。 递归方法: ```c #include <stdio.h> struct Node { int data; struct Node* next; }; void reversePrint(struct Node* head) { if (head == NULL) { return; } reversePrint(head->next); printf("%d ", head->data); } int main() { struct Node* head = NULL; struct Node* second = NULL; struct Node* third = NULL; head = (struct Node*)malloc(sizeof(struct Node)); second = (struct Node*)malloc(sizeof(struct Node)); third = (struct Node*)malloc(sizeof(struct Node)); head->data = 1; head->next = second; second->data = 2; second->next = third; third->data = 3; third->next = NULL; reversePrint(head); return 0; } ``` 迭代方法: ```c #include <stdio.h> struct Node { int data; struct Node* next; }; void reversePrint(struct Node* head) { struct Node* prev = NULL; struct Node* current = head; struct Node* next = NULL; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } head = prev; struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } } int main() { struct Node* head = NULL; struct Node* second = NULL; struct Node* third = NULL; head = (struct Node*)malloc(sizeof(struct Node)); second = (struct Node*)malloc(sizeof(struct Node)); third = (struct Node*)malloc(sizeof(struct Node)); head->data = 1; head->next = second; second->data = 2; second->next = third; third->data = 3; third->next = NULL; reversePrint(head); return 0; } ``` 以上两种方法都能实现链表逆序输出,递归方法通过递归调用实现逆序输出,迭代方法则通过交换链表节点的指针实现逆序输出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值