使用尾插法建立一张带头结点的单链表L,并使L的长度大于10。 要求: (1)单链表的长度 (2)查找第三个元素的值 (3)将值为100的新结点*s插入到单链表L第4个结点位置。 (4)删除单链表L的第4个结点。。代码
时间: 2024-05-29 22:13:12 浏览: 87
好的,我理解了你的问题。以下是回答:
代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}Node;
Node* CreateList(int n);//创建单链表
int Length(Node* L);//计算单链表长度
int FindThird(Node* L);//查找第三个元素的值
void Insert(Node* L, int location, int value);//将值为100的新结点插入到单链表L第四个结点位置
void Delete(Node* L, int location);//删除单链表L的第四个结点
void PrintList(Node* L);//打印单链表L
int main(){
int n = 11;//单链表长度大于10
Node* L = CreateList(n);
printf("单链表长度:%d\n",Length(L));
printf("第三个元素的值:%d\n",FindThird(L));
Insert(L, 4, 100);
printf("将值为100的新结点插入到单链表L第四个结点位置后,单链表L的值为:\n");
PrintList(L);
Delete(L, 4);
printf("删除单链表L的第四个结点后,单链表L的值为:\n");
PrintList(L);
return 0;
}
Node* CreateList(int n){
Node* L = (Node*)malloc(sizeof(Node));
L->data = -1;
L->next = NULL;
Node* p = L;
int i;
for(i = 1; i <= n; i++){
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = i;
temp->next = NULL;
p->next = temp;
p = temp;
}
return L;
}
int Length(Node* L){
int len = 0;
Node* p = L->next;
while(p != NULL){
len++;
p = p->next;
}
return len;
}
int FindThird(Node* L){
Node* p = L->next->next->next;
return p->data;
}
void Insert(Node* L, int location, int value){
Node* p = L;
int i = 0;
while(p != NULL){
if(i == location - 1){
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = value;
temp->next = p->next;
p->next = temp;
break;
}
i++;
p = p->next;
}
}
void Delete(Node* L, int location){
Node* p = L;
int i = 0;
while(p != NULL){
if(i == location - 1){
Node* temp = p->next;
p->next = temp->next;
free(temp);
break;
}
i++;
p = p->next;
}
}
void PrintList(Node* L){
Node* p = L->next;
while(p != NULL){
printf("%d ",p->data);
p = p->next;
}printf("\n");
}
说明:
在该程序中,首先我们定义了一个链表节点结构体Node,包含一个整型数据data和一个指向下一个节点的指针next。在CreateList中,我们先创建一个头节点L,将其值设为-1,并将其指针指向NULL。然后,我们通过for循环创建n个新节点,并将其添加到链表末尾,最后返回头节点L。
在Length中,我们遍历整个链表,计算出链表长度并返回。
在FindThird中,我们直接通过指针p找到L的下一个节点的下一个节点的下一个节点,即第三个元素,并返回其值。
在Insert中,我们先将链表指针p指向头节点L,然后在while循环中遍历链表,直到找到要插入的位置。我们在该位置处创建一个新节点,并将其插入到链表中。最后,我们将插入的节点位置+1(因为头节点的位置为0),并跳过新插入的节点。
在Delete中,我们与Insert类似地遍历链表,找到需要删除的节点,并释放其内存。最后,我们将被删除节点的位置+1(因为头节点的位置为0),并跳过被删除的节点。
在PrintList中,我们遍历整个链表,并打印出每个节点的值。
阅读全文
相关推荐














