#include <iostream>
using namespace std;
typedef int elemType;
typedef struct LinkList{
elemType data;
struct LinkList *next;
}Node, *pNode;
pNode CreateLinkList(int len)
{
elemType value;
pNode head = (pNode)malloc(sizeof(Node));
head->next = NULL;
if(head == NULL){
printf("Memory allocation error");
exit(-1);
}
else{
pNode tail = head;
for(int i = 0; i < len; i++)
{
pNode p = (pNode)malloc(sizeof(Node));
if(p == NULL){
printf("Memory allocation error");
exit(-1);
}
else{
printf("Please input the value: ");
scanf("%d", &value);
p->data = value;
tail->next = p;
p->next = NULL;
tail = p;
}
}
}
return head;
}
bool InsertList(LinkList* head, int pos, elemType value)
{
pNode p = head;
int i = 0;
while(p != NULL && i < pos - 1)
{
p = p->next;
i++;
}
if(p == NULL || i > pos - 1){
return false;
}
pNode q = (pNode)malloc(sizeof(Node));
q->data = value;
q->next = p->next;
p->next = q;
return true;
}
bool DeleteNode(LinkList* head, int pos)
{
int i = 0;
pNode p = head;
while(p != NULL && i < pos - 1)
{
p = p->next;
i++;
}
if(p == NULL || i > pos - 1){
return false;
}
pNode q = p->next;
p->next = q->next;
free(q);
q = NULL;
return true;
}
void PrintList(LinkList* head)
{
pNode p = head->next;
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
}
int main()
{
LinkList* list = CreateLinkList(3);
if(DeleteNode(list,2));
PrintList(list);
system("pause");
}
链表操作---
最新推荐文章于 2024-05-02 23:57:32 发布