写一个创建单链表的代码
时间: 2024-05-05 18:16:07 浏览: 8
以下是一个创建单链表的Python代码示例:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def create_linked_list(nums):
head = ListNode()
cur = head
for num in nums:
cur.next = ListNode(num)
cur = cur.next
return head.next
```
使用示例:
```python
>>> nums = [1, 2, 3, 4, 5]
>>> head = create_linked_list(nums)
>>> while head:
... print(head.val)
... head = head.next
...
1
2
3
4
5
```
相关问题
用c语言写一个创建单链表的代码
以下是C语言实现创建单链表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data; // 数据域
struct Node* next; // 指针域,指向下一个节点
};
// 创建链表
struct Node* createList(int* arr, int len) {
struct Node* head = NULL; // 头节点指针
struct Node* tail = NULL; // 尾节点指针
// 循环创建节点
for (int i = 0; i < len; i++) {
// 创建节点
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = arr[i];
node->next = NULL;
// 如果链表为空,将头节点指向当前节点
if (head == NULL) {
head = node;
tail = node;
} else {
// 将新节点插入到尾节点后面
tail->next = node;
tail = node;
}
}
return head; // 返回头节点指针
}
// 打印链表
void printList(struct Node* head) {
struct Node* p = head; // 用指针p遍历链表
// 循环打印链表节点的数据
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int len = sizeof(arr) / sizeof(arr[0]);
// 创建链表
struct Node* head = createList(arr, len);
// 打印链表
printList(head);
return 0;
}
```
运行结果:
```
1 2 3 4 5
```
用C语言写一段创建单链表的代码
以下是创建单链表的C语言代码:
#include<stdio.h>
#include<stdlib.h>
//定义链表结构体
struct node
{
int data;
struct node *next;
};
typedef struct node NODE;
typedef NODE *LINK;
int main()
{
LINK head = NULL;
LINK tail = NULL;
LINK new_node = NULL;
int num = 0;
//创建链表
printf("请输入一个整数作为链表的元素(输入-1结束):\n");
while(1)
{
scanf("%d",&num);
if(num == -1)
{
break;
}
new_node = (LINK)malloc(sizeof(NODE));
new_node->data = num;
new_node->next = NULL;
if(head == NULL)
{
head = new_node;
tail = new_node;
}
else
{
tail->next = new_node;
tail = new_node;
}
}
//遍历链表
printf("链表的元素为:");
LINK p = head;
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
//释放链表内存
p = head;
while(p != NULL)
{
head = head->next;
free(p);
p = head;
}
return 0;
}