标题 链表的基本操作
一.单向链表的创建,节点的插入和删除
1.链表创建:(注意链表的第一个节点是空的)
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct LNode{
int data;
struct LNode*next;
}LNode,*Linklist;
Linklist Createlist(int n);
void print(Linklist h);
int main()
{
Linklist Head=NULL;
int n;
scanf("%d",&n);
Head=Createlist(n);
printf("刚刚创建的各个链表元素的值为:\n");
print(Head);
printf("\n");
system("pause");
return 0;
}
Linklist Createlist(int n)
{
Linklist L,p,q;
int i;
L=(LNode*)malloc(sizeof(LNode));
if(!L) return 0;
L->next=NULL;
q=L;
for(i=1;i<=n;i++)
{
p=(Linklist)malloc(sizeof(LNode));
printf("请输入第%d个元素的值:\n",i);
scanf("%d",&(p->data));
p->next=NULL;
q->next=p;
q=p;
}
return L;
}
void print(Linklist h)
{
Linklist p=h->next;
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
}
2 删除某个节点
设计函数,利用循环找到链表节点,直接用free()函数清除
3 插入节点
同样设计函数,找到要插入的位置
核心代码:
s=(Linklist)malloc(sizeof(LNode));
s->next=p->next;
p->next=s;
s->data="想要插入的元素”;
return OK;
二、双向链表
其实双向链表与单向的区别仅仅是每个节点多了一个指向前一个节点的指针,下面介绍其简单操作
1 双向链表的创建:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct DoubleLinkNode
{
int data;
struct DoubleLinkNode *prev;
struct DoubleLinkNode *next;
}Node;
/* 创建一个带头节点的双向链表 */
Node*Create_Double_link()
{
Node*head;
Node*pnext;
Node*plast;
int i,n;
head=(Node*)malloc(sizeof(Node));
assert(NULL != head);
head->prev=NULL;
head->next=NULL;
printf("please input the length of the double linked list:");
scanf("%d",&n);
while(n!=0)
{
plast=head;
for(i=0;i<n;i++)
{
pnext=(Node*)malloc(sizeof(Node));
printf("向第%d个节点输入数据:",i+1);
scanf("%d",&pnext->data);
plast->next=pnext;
pnext->prev=plast;
plast=plast->next;
}
pnext->next=NULL;
break;
}
return head;
}
/* 输出每一个节点的数据 */
void print(Node*head)
{
Node*temp;
int j=0;
temp=head;
while(temp->next!=NULL)
{
j++;
printf("输出第%d个节点的数据:%d\n",j,temp->next->data);
temp=temp->next;
}
printf("输出第%d个节点的数据:%p\n",j+1,temp->next);
}
2 插入节点
int InsertNode(Node* head)
{
Node*new;
Node*pnext=head;
int i=0;
int n;
printf("please input the location which is inserted:");
scanf("%d",&n);
while((i<n) && (pnext!=NULL))
{
i++;
pnext=pnext->next;
}
if(pnext==NULL)
{
printf("请重输"\n);
}
else
{
new=(Node*)malloc(sizeof(Node));
printf("请在新插入的节点中输入数据:");
scanf("%d",&new->data);
new->next=pnext->next;
pnext->next=new;
new->prev=pnext;
}
return 0;
}
3 删除节点
free();
三、循环链表
1 创建
Linklist Creat_list(Linklist head) {
LNode *node = NULL;
LNode *end = NULL;
head = (Linklist)malloc(sizeof(LNode));
head->next = NULL;
head->data = -1;
end = head;
int count = 0;
printf("Input node numbers: ");
scanf("%d", &count);
for (int i = 0; i < count; i++) {
node = (LNode*)malloc(sizeof(LNode));
node->data = i;
end->next = node;
end = node;
}
end->next = head; // 将尾结点的指针指向头结点
return head;
}
而要对循环链表进行计数等操作不能再像前面那样判断指针是否指向NULL,
我们可以把head赋一个值,当得到这个值即代表循环了一次。
最后说一点,双向循环链表即是把head的prior指针指向最后一个节点即可