C和python创建链表的方法

本文深入讲解了使用Python和C语言创建及打印链表的方法。通过详细的代码示例,读者可以了解链表的基本结构和操作流程,包括节点的定义、链表的创建、元素的添加以及链表的遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.python创建和打印链表:

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    def printListFromTailToHead(self, listNode):
        a=listNode
        while a:
            print(a.val)
            a=a.next
a1=ListNode(5)
a2=ListNode(3)
a3=ListNode(8)
a4=ListNode(1)
a1.next=a2
a2.next=a3
a3.next=a4
s=Solution()
s.printListFromTailToHead(a1)

2.C语言创建和打印链表
头文件12.h

#ifndef __LIST_HEAD__
#define __LIST_HEAD__
typedef struct _node
{
	int value;
	struct _node* next;
}Node;
#endif

源代码文件:

#include<stdio.h>
#include"12.h" 
#include<stdlib.h>
typedef struct _list {
	Node* head;
}List;
void add(List* plist, int number)
{
	Node* p = (Node*)malloc(sizeof(Node));
	p->value = number;
	p->next = NULL;
	Node* last = plist->head;
	if (last) {
		while (last->next) {
			last = last->next;
		}
		last->next = p;
	}
	else
	{
		plist->head = p;
	}
}
int main(int argc, char const *argv[])
{
	List list;
	list.head= NULL;
	int number;
	do
	{
		scanf("%d", &number);
		if (number!=-1)
		{
			add(&list, number);
		}
	} while (number!=-1);
	Node *p;
	for (p = list.head; p; p = p->next)
	{
		printf("%d\t", p->value);
	}
	printf("\n");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值