05_从头到尾打印链表

题目:输入一个链表的头结点,从尾到头打印链表每个结点的值。

思路:从头到尾遍历链表,并用一个栈存储每个结点的值,之后出栈输出值即可。

Java版本:

import java.util.Stack;

public class Test {

    public static class ListNode{
        int value;//结点的值
        ListNode nxt;//下一个节点
    }

    //采用栈的方式
    public static void printListInverselyUsingIteration(ListNode root){
        //创建一个栈
        Stack<ListNode> stack = new Stack<>();
        if(root == null){
            System.out.println("链表为空");
        }
        while(root != null){
            stack.push(root);
            root = root.nxt;
        }
        ListNode tmp;
        while(!stack.isEmpty()){
            tmp = stack.pop();
            System.out.print(tmp.value+" ");
        }
    }

    public static void creatListNode(ListNode root1,int value,ListNode root2){
        if(root1 == null){
            System.out.println("链表为空");
        }
        root1.value = value;
        root1.nxt = root2;
        System.out.print(value + " ");
    }

    public static void main(String[] args) {

        ListNode root1 = new ListNode();
        ListNode root2 = new ListNode();
        ListNode root3 = new ListNode();
        ListNode root4 = new ListNode();
        ListNode root5 = new ListNode();
        ListNode root6 = new ListNode();

        System.out.print("链表反转前:");
        creatListNode(root1,12,root2);
        creatListNode(root2, 4,root3);
        creatListNode(root3,14,root4);
        creatListNode(root4, 8,root5);
        creatListNode(root5, 2,root6);
        creatListNode(root6,30, null);

        System.out.println();
        System.out.print("链表反转后:");
        printListInverselyUsingIteration(root1);
        System.out.println();
        printListInverselyUsingIteration(null);
    }
}

这里写图片描述

Python版本:

# -*- coding: utf-8 -*-
class ListNode:
    def __init__(self,x=None,next1=None):
        self.value = x
        self.next = next1

def creatListNode(node1,value,node2):
    if node1 == None:
        print('')
    node1 = ListNode(value)
    node1.next = node2

def printListFromTailToHead(ListNode):
    if ListNode.value == None:
        return

    List=[]
    head = ListNode
    while head:
        # 在第0个位置处插入结点,即最前面
        List.insert(0,head.value)
        head = head.next

    print(List)
    return 1

List=[15,11,7,18,2,4,11,6]
length = len(List)
Node =[]
for i in range(length):
    Node.append(ListNode(List[i]))

for j in range(length):
    if (j==length-1):
        Node[j].next=None
    else:
        Node[j].next = Node[j+1]

print('链表反转前:')
print(List)
print('链表反转后:')
printListFromTailToHead(Node[0])

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值