记录自己刷题过程day1--剑指 Offer 06. 从尾到头打印链表

剑指 Offer 06. 从尾到头打印链表-easy

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:
输入:head = [1,3,2]
输出:[2,3,1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof

解法:遍历链表,放入list中,从后往前循环list放入数组中。

    public int[] reversePrint(ListNode head) {
    	//特殊判断
        if(head == null) return new int[0];
        List<Integer> sb = new ArrayList<>();
        //循环遍历链表放入list中
        while (head != null){
            sb.add(head.val);
            head = head.next;
        }
        int[] result = new int[sb.size()];
        int n = 0;
        for (int i = sb.size() - 1; i >= 0; i--) {
            result[n] = sb.get(i);
            n++;
        }
        return result;
    }

以上~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一元多项式表示为 a_n * x^n + a_(n-1) * x^(n-1) + ... + a_1 * x + a_0,其中 a_i 是系数,x 是变量,n 是数。 要实现一元多项式的链表表示,我们可以定义一个结构体来表示多项式的每一项,包括系数和数,并使用针来连接每一项。示例代码如下: ``` #include <stdio.h> #include <stdlib.h> // 定义多项式项的结构体 typedef struct Node { int coefficient; // 系数 int exponent; // 数 struct Node* next; // 下一项 } Node; // 创建多项式 Node* createPolynomial() { Node* head = (Node*)malloc(sizeof(Node)); // 创建头结点 head->next = NULL; Node* current = head; int coefficient, exponent; printf("请输入项数: "); int count; scanf("%d", &count); for (int i = 0; i < count; i++) { printf("请输入第%d项的系数和数: ", i + 1); scanf("%d %d", &coefficient, &exponent); Node* newNode = (Node*)malloc(sizeof(Node)); newNode->coefficient = coefficient; newNode->exponent = exponent; newNode->next = NULL; current->next = newNode; current = newNode; } return head; } // 输出多项式 void printPolynomial(Node* polynomial) { Node* current = polynomial->next; while (current != NULL) { printf("%dx^%d", current->coefficient, current->exponent); if (current->next != NULL) { printf(" + "); } current = current->next; } printf("\n"); } int main() { Node* polynomial = createPolynomial(); printf("多项式为: "); printPolynomial(polynomial); return 0; } ``` 通过上述代码,我们可以创建一个包含多项式的链表,并打印出其内容。你可以根据需要对多项式链表进行其他基本操作的实现,如插入、删除、合并等。 此外,你还可以在多项式链表的基础上实现一个简单的多项式计算器。你可以根据用户输入的操作,对多项式进行加法、减法、乘法等运算,最后输出结果。在计算过程中,你需要实现将多项式链表转换为多项式数组的功能,并根据相应的运算规则进行计算。这样,你就可以通过简单的计算器来计算和操作一元多项式了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值