#include<stdio.h>
#include<stdlib.h>
/*
struct node{};
node
*/
typedef struct node{
int data;
struct node *next;
}ListNode,*LinkList;
//头插法建立单链表
LinkList CreateListOnHead(){
int x = 1;
ListNode *p;
LinkList head;
head = (LinkList)malloc(sizeof(ListNode));
head->next = NULL;
//scanf("%d",&x);
//printf("%d",x);
while(x!=9){
p = (ListNode*)malloc(sizeof(ListNode));
p->data = x;
x++;
p->next = head->next;
head->next = p;
//scanf("%d",x);
}
return head;
}
//尾插法建立单链表
LinkList CreateListOnTail(){
int x = 1;
ListNode *s;//指向新的node
ListNode *p;//指向链尾node
LinkList head = (LinkList)malloc(sizeof(ListNode));
p = head;
//scanf("%d",&x);
//getchar();
while(x!=9){
s = (ListNode*)malloc(sizeof(ListNode));
s->data = x;
p->next = s;
p = s;
//scanf("%d",&x);
//getchar();
x++;
}
s->next = NULL;
return head;
}
//按序号查找节点,返回节点指针
ListNode *GetElemByi(LinkList l,int i){
ListNode *p;//用来查找节点
p = l->next;//有头节点,所以next指向第一个节点
int index = 1;//记位置
while(index!=i&&p!=NULL) {
p = p->next;
index++;
}
return p;
}
//在第i个位置后面插入节点
bool Insert_to_i(LinkList &l,int i,int x){
ListNode *p = GetElemByi(l,i);
if(p==NULL)
return false;
ListNode *s = (ListNode*)malloc(sizeof(ListNode));
s->data = x;
s->next = p->next;
p->next = s;
return true;
}
//删除值为x的节点 ,递归法
void Del_x(LinkList &l,int x){
ListNode *p;
if(l==NULL){
return;
}
if(l->data==x){
p = l;
l = l->next;
free(p);
Del_x(l,x);
}
else{
Del_x(l->next,x);
}
}
int main(){
//头插法建立单链表
printf("头插法建立单链表\n");
LinkList head = CreateListOnHead();
ListNode *p = head->next;
while(p!=NULL){
printf("%d ",p->data);
p = p->next;
}
printf("\n\n");
//尾插法建立单链表
printf("尾插法建立单链表\n");
head = CreateListOnTail();
p = head->next;
while(p!=NULL){
printf("%d ",p->data);
p = p->next;
}
printf("\n\n");
//按序号查询节点
printf("按序号查找节点\n");
p = GetElemByi(head,4);
printf("%d",p->data);
printf("\n\n");
//在第i个位置后面插入节点
printf("在第i个位置后面插入节点\n");
Insert_to_i(head,5,55);
p = head->next;
while(p!=NULL){
printf("%d ",p->data);
p = p->next;
}
printf("\n\n");
//删除值尾x的节点
printf("删除值尾x的节点\n");
Del_x(head->next,5);
p = head->next;
while(p!=NULL){
printf("%d ",p->data);
p = p->next;
}
printf("\n\n");
}
运行结果:
8 7 6 5 4 3 2 1
尾插法建立单链表
1 2 3 4 5 6 7 8
按序号查找节点
4
在第i个位置后面插入节点
1 2 3 4 5 55 6 7 8
删除值尾x的节点
1 2 3 4 55 6 7 8