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;
}