反向打印链表

反向打印链表先将链表存储在栈中,然后将栈中的元素输出,就可以实现链表的反向打印了

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class PrintListReversing {
    
    public static void main(String[] args) {
        List<Integer> list = new LinkedList<Integer>();
        for (int i=0; i<10; i++)
            list.add(i);
        printListReversing(list);
    }
    
    static void printListReversing(List<Integer> list) {
        Stack<Integer> stack = new Stack<Integer>();
        for (int i : list) {
            stack.push(i);
        }
        int size = stack.size();
        for (int i=0; i<size; i++)
            System.out.println(stack.pop());
    }
}

转载于:https://www.cnblogs.com/xidongyu/p/7041039.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将链表反向连接,可以使用三个指针来完成操作。首先,将当前节点的下一个节点保存在一个临时指针中,然后将当前节点的下一个节点指向前一个节点,最后将前一个节点指向当前节点。重复这个过程直到遍历完整个链表。最后,将最后一个节点设置为新的头节点。 以下是一个示例代码来演示如何在C语言中将链表反向连接: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构 struct Node { int data; struct Node* next; }; // 反向连接链表函数 struct Node* reverseLinkedList(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; return head; } // 打印链表函数 void printLinkedList(struct Node* head) { struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } // 主函数 int main() { // 创建链表 struct Node* head = (struct Node*)malloc(sizeof(struct Node)); struct Node* second = (struct Node*)malloc(sizeof(struct Node)); 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; printf("原始链表:"); printLinkedList(head); // 反向连接链表 head = reverseLinkedList(head); printf("反向连接后的链表:"); printLinkedList(head); return 0; } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值