创建一个不带头结点的链表
时间: 2023-04-09 13:04:53 浏览: 97
可以使用以下代码创建一个不带头结点的链表:
```
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add_node(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
```
这个代码片段定义了一个 Node 类和一个 LinkedList 类。Node 类表示链表中的一个节点,它包含一个数据项和一个指向下一个节点的指针。LinkedList 类表示整个链表,它包含一个指向链表头部的指针。add_node 方法用于向链表中添加一个新节点。如果链表为空,则将新节点设置为头节点;否则,遍历链表直到找到最后一个节点,然后将新节点添加到链表的末尾。
相关问题
请用C语言创建一个不带头结点的单链表
好的,以下是创建一个不带头结点的单链表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
int main() {
struct Node *head = NULL, *tail = NULL, *temp = NULL;
int num;
printf("请输入整数,输入 -1 结束:\n");
scanf("%d", &num);
while (num != -1) {
temp = (struct Node *) malloc(sizeof(struct Node));
temp -> data = num;
temp -> next = NULL;
if (head == NULL) {
head = temp;
tail = temp;
} else {
tail -> next = temp;
tail = temp;
}
scanf("%d", &num);
}
printf("链表的值为:\n");
temp = head;
while (temp != NULL) {
printf("%d ", temp -> data);
temp = temp -> next;
}
return 0;
}
```
希望这能够帮到您!
创建一个带头结点的链表
可以参考以下代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createList(int n) {
Node *head = (Node *)malloc(sizeof(Node));
head->next = NULL;
Node *tail = head;
for (int i = 0; i < n; i++) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = i;
node->next = NULL;
tail->next = node;
tail = node;
}
return head;
}
void printList(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node *head = createList(5);
printList(head);
return 0;
}
```
这段代码实现了创建一个带头结点的链表,其中头结点不存储数据,只用来指向链表的第一个结点。