定义:
#include"stdio.h"
typedef int DataType;
typedef struct node{
DataType data;
struct node *next;
}ListNode;
1.头插入法创建单链表
ListNode *CrateListF(DataType *x,int n){
int i;
ListNode *head,*s;
head=NULL;
for(i=0;i<n;i++){
s=(ListNode*)malloc(sizeof(ListNode));
s->data=x[i];
s->next=head;
head=s;
}
return head;
}
2.尾插入法创建单链表
ListNode *CreateListL(DataType *x,int n){
ListNode *s,*r,*head;
int i;
head=(ListNode*)malloc(sizeof(ListNode));
head=NULL:
r=head;
for(i=0;i<n;i++){
s=(ListNode*)malloc(sizeof(ListNode));
s->data=x[i];
r->next=s;
r=s;
}
r->next=NULL;
return head;
}
3.求不带头节点单链表头节点的长度
int LengthList(ListNode *head){
ListNode *p;
int i;
p=head;
while(p->next!=NULL){
p=p->next;
i++;
}
return i;
}
4.输出不带头节点单链表
void PrintList(ListNode *head){
ListNode *p;
p=head;
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
printf("%d ",p->data);
}
5.获取单链表的头节点
ListNode *GetHeadNode(ListNode *head){
return head->data;
}
6.获取单链表节点的
ListNode *GetNode(ListNode *head,int k){
ListNode *p;
int i;
p=head;
for(i=0;i<k;i++){
p=p->next;
}
return p->data;
}
7.单链表的插入
void InsertList(ListNode *head,DataType x,int k){
int i;
ListNode *p,*s;
p=head;
for(i=0;i<k;i+){
p=p->next;
}
s=(ListNode*)malloc(sizeof(ListNode));
s->data=x;
s->next=p->next;
p->next=s;
free(s);
}
8.单链表的删除
void DeletNode(ListNode *head,int k){
ListNode *p,*s;
int i;
p=head;
for(i=0;i<k-1;i++){
p=p->next;
}//找到k节点的前一个节点
s=p->next;
p->next=s->next;
free(s);
}
主函数测试
main(){
ListNode *fp,*lp;
int arr[]={6,2,15,8,9,3};
int n=6;
fp=CreateListF(arr,n);//带头节点
PrintList(fp);
ql=CreatListL(arr,n);//带头节点
PrintList(lp);
InsertList(ql->next,7,2);//插入节点
PrintList(ql);
DeletList(ql->next,4);//删除节点
PrintList(ql);
}