链栈是不是就是头插法的链表?
时间: 2023-04-08 20:04:39 浏览: 122
链栈是一种基于链表实现的栈结构,它与头插法的链表有些相似,但并不完全相同。在链栈中,栈顶元素对应链表的头部,而栈底元素对应链表的尾部。每次入栈操作都是在栈顶插入新元素,而出栈操作则是从栈顶删除元素。因此,链栈的插入和删除操作都是在链表的头部进行的,但链栈还需要维护栈顶指针,以便快速访问栈顶元素。
相关问题
用C++写一个头插法链表
好的,我可以回答这个问题。以下是用 C 语言写一个头插法链表的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
printf("链表的元为: ");
printList(head);
return ;
}
```
这个程序会创建一个头指针 `head`,并使用 `insert` 函数来插入新的元。每次插入新元素时,都会将新元素插入到链表的头部。最后,使用 `printList` 函数来打印链表的所有元素。
头插法反转链表C语言代码
头插法是一种反转链表的方法,它通过将原链表的每个节点插入到新链表的头部,从而实现链表的反转。下面是使用头插法反转链表的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode* next;
};
// 头插法反转链表
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* newHead = NULL; // 新链表的头节点
while (head != NULL) {
struct ListNode* nextNode = head->next; // 保存下一个节点的指针
head->next = newHead; // 将当前节点插入到新链表的头部
newHead = head; // 更新新链表的头节点
head = nextNode; // 移动到下一个节点
}
return newHead;
}
// 创建链表
struct ListNode* createList(int* nums, int size) {
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
for (int i = 0; i < size; i++) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = nums[i];
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 打印链表
void printList(struct ListNode* head) {
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
int nums[] = {1, 2, 3, 4, 5};
int size = sizeof(nums) / sizeof(nums[0]);
struct ListNode* head = createList(nums, size);
printf("原链表:");
printList(head);
struct ListNode* newHead = reverseList(head);
printf("反转后的链表:");
printList(newHead);
return 0;
}
```