#include <stdio.h>
#include <stdlib.h>
struct Linklist{
char data;
struct Linklist * next;
};
Linklist * createLinklist(){
Linklist * head,* p;
char x;
head = (Linklist *)malloc(sizeof(Linklist));
head->next = NULL;
printf("please input data!\n");
scanf("%c",&x);
while(x != '\n'){
p = (Linklist *)malloc(sizeof(Linklist));
p->data = x;
p->next = head->next;
head->next = p;
scanf("%c",&x);
}
return head;
}
/*
Linklist * createLinklist(){
Linklist * head,* p,*q;
char x;
head = (Linklist *)malloc(sizeof(Linklist));
head->next = NULL;
q = head;
printf("please input data!\n");
scanf("%c",&x);
while(x != '\n'){
p = (Linklist *)malloc(sizeof(Linklist));
p->data = x;
p->next = NULL;
q->next = p;
q = p;
scanf("%c",&x);
}
return head;
}
*/
Linklist * location(Linklist * head,int i){
Linklist * p;
int j = 0;
p = head;
while(p!= NULL && j<i){
p = p->next;
j++;
}
return p;
}
Linklist * location2(Linklist * head,char x){
Linklist * p;
p = head->next;
while(p->data != x){
p = p->next;
}
return p;
}
void insert(Linklist * head,int i,char x){
Linklist * p;
Linklist * q;
p = location(head,i-1);
if(p == NULL){
printf("the location of i-1 doesn't exist1\n");
}else{
q = (Linklist *)malloc(sizeof(Linklist));
q->data = x;
q->next = p->next;
p->next = q;
}
}
void delLinklist(Linklist * head,int i){
Linklist * p;
Linklist * q;
p = location(head,i-1);
if(p == NULL){
printf("the location i-1 doesn't exist!\n");
}else if(p->next == NULL){
printf("the location i doesn't exist!\n");
}else{
q = p->next;
p->next = q->next;
free(q);
}
}
int lengthLinklist(Linklist * head){
int i=0;
Linklist * p = head;
while(p!=NULL){
i++;
p = p->next;
}
return i-1;
}
void reverse(Linklist * head){
Linklist * p,*q;
p = head->next;
head->next = NULL;
while(p!=NULL){
q = p;
p = p->next;
q->next = head->next;
head->next = q;
}
}
void traverse(Linklist * head){
Linklist * p;
p = head->next;
printf("the elements of the list are:\n");
while(p!=NULL){
printf("%c",p->data);
p = p->next;
}
}
int main(){
Linklist * head;
Linklist * p;
// Linklist * q;
int x;
int len;
// char y;
head = createLinklist();
traverse(head);
printf("\n");
printf("the length of the list is:\n");
len = lengthLinklist(head);
printf("%d",len);
printf("\n");
printf("please input the location\n");
scanf("%d",&x);
p = location(head,x);
if(p != NULL){
printf("%c",p->data);
}else{
printf("the position doesn't exist!\n");
}
/*
printf("please input the value\n");
scanf("%c",&y);
q = location2(head,y);
if(q != NULL){
printf("the value exist!\n");
}else{
printf("the value doesn't exist!\n");
}
*/
printf("\nafter insert:\n");
insert(head,4,'h');
traverse(head);
printf("\n\n");
printf("after delete:\n");
delLinklist(head,3);
traverse(head);
printf("\n\n");
printf("after reverse:\n");
reverse(head);
traverse(head);
printf("\n");
return 0;
}
单链表的基本操作
最新推荐文章于 2022-08-16 21:17:20 发布