#include "stdio.h"
#include "stdlib.h"
#include "string.h"
typedef struct SNode {
char data[100];
struct SNode *next;
} SNode;
void getInput(SNode *sNode) {
printf("请输入data:");
scanf("%s", sNode->data);
}
void tailInsertData(SNode *sNode) {
SNode *data;
data = (SNode *) malloc(sizeof(SNode));
if (data == NULL) {
printf("申请地址失败\n");
exit(1);
}
getInput(data);
while (sNode->next != NULL) {
sNode = sNode->next;
}
sNode->next = data;
data->next = NULL;
}
void headInsertData(SNode *sNode) {
SNode *data;
data = (struct SNode *) malloc(sizeof(struct SNode));
if (data == NULL) {
printf("申请地址失败\n");
exit(1);
}
getInput(data);
SNode *temp;
if (sNode->next != NULL) {
temp = sNode->next;
sNode->next = data;
data->next = temp;
} else {
sNode->next = data;
data->next = NULL;
}
}
void display(SNode *sNode) {
while (sNode != NULL) {
printf("data = %s\n", sNode->data);
sNode = sNode->next;
}
}
int calLength(SNode *sNode) {
int count = 0;
SNode *p;
p = sNode->next;
while (p != NULL) {
p = p->next;
count += 1;
}
printf("链表的长度为:%d\n", count);
return count;
}
void destroy(SNode **sNode) {
if(*sNode == NULL){
printf("链表已销毁\n");
}else{
SNode *p = NULL;
while (*sNode) {
p = *sNode;
*sNode = (*sNode)->next;
free(p);
}
printf("destroy success!\n");
}
}
void clear(SNode **sNode){
if((*sNode)->next == NULL){
printf("链表已为空\n");
}else{
SNode *p, *q;
p = (*sNode)->next;
(*sNode)->next = NULL;
while(p){
q = p;
p = p->next;
free(q);
}
}
}
void deleteTailData(SNode *sNode){
if(sNode->next == NULL){
printf("表为空,无法删除,可以销毁表\n");
}else{
SNode *last;
while (sNode->next){
last = sNode;
sNode = sNode->next;
}
last->next = NULL;
free(sNode->next);
printf("成功删除尾部数据\n");
}
}
void deleteHeadData(SNode *sNode){
if(sNode->next == NULL){
printf("表为空,无法删除,可以销毁表\n");
}else{
SNode *head;
head = sNode->next;
if(head->next){
sNode->next = head->next;
}else{
sNode->next = NULL;
}
free(head);
printf("成功删除头部数据\n");
}
}
void deleteIDate(SNode *sNode, int i) {
if(i > calLength(sNode)){
printf("链表长度不够\n");
}else{
int count = 0;
SNode *pro, *next;
if(i == 1){
pro = sNode->next;
sNode->next = pro->next;
free(pro);
printf("已经删除\n");
}else{
while (sNode != NULL) {
count += 1;
pro = sNode;
if(count == i){
break;
}
sNode = sNode->next;
}
next = sNode->next->next;
pro->next = next;
free(next);
printf("已经删除\n");
}
}
}
void queryIDate(SNode *sNode, int i) {
if(i> calLength(sNode)){
printf("链表长度不够\n");
}else{
int count = 0;
while (sNode != NULL) {
count += 1;
sNode = sNode->next;
if(count == i){
printf("第 %d 个元素是:%s\n", count, sNode->data);
}
}
}
}
int queryLocateData(SNode *sNode, char e[]){
int count = -1;
while (sNode != NULL) {
count += 1;
if(strcmp(sNode->data, e) == 0){
printf("元素 %s 的位置是:%d\n", sNode->data, count);
}
sNode = sNode->next;
}
return count;
}
int main() {
struct SNode *l = NULL;
l = (struct SNode *) malloc(sizeof(struct SNode));
l->next = NULL;
strcpy(l->data, "我是头结点");
headInsertData(l);
return 0;
}