#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct Node
{
char data[64];
Node* next;
}Node;
Node* creatSList(){
Node* pHead = NULL;
Node* pCur = NULL;
Node* pMalloc = NULL;
char name[64]={0};
pMalloc = (Node*)malloc(sizeof(Node));
printf("请输入数据,以-1结束:\n");
scanf("%s",name);
strcpy(pMalloc->data,name);
pHead = pMalloc;
pCur = pHead;
while(1){
pMalloc = (Node*)malloc(sizeof(Node));
printf("请输入数据:");
scanf("%s",name);
if(strcmp(name,"-1")==0)
break;
strcpy(pMalloc->data,name);
pCur->next = pMalloc;//连接新创建的节点
pCur = pMalloc;
}
pCur->next = NULL;//链表尾部
return pHead;
}
int printSList(Node* p){
while(p){
puts(p->data);
p = p->next;
}
return 0;
}
int insertSlist(Node** pHead,int pos){
Node* pMalloc = NULL;
Node* pCur = NULL;
char data[64]={0};
pMalloc = (Node*)malloc(sizeof(Node));
printf("请输入数据:");
scanf("%s",data);
strcpy(pMalloc->data,data);
if (pos==0)
{
pMalloc->next = *pHead;
*pHead = pMalloc;
}else{
pCur = *pHead;
for(int i=1;i<pos;i++){
pCur = pCur->next;
}
pMalloc->next = pCur->next;
pCur->next = pMalloc;
}
return 0;
}
int deleteSList(Node** pHead,int pos){
Node* pCur = NULL;
Node* pTmp = NULL;
if (pos==0)
{
pCur = *pHead;
*pHead = pCur->next;
}else{
pCur = *pHead;
for(int i=1;i<pos;i++){
pCur = pCur->next;
}
pTmp = pCur->next;
pCur->next = pTmp->next;
}
return 0;
}
int reverseSList(Node** pHead){
Node* pCur = NULL;
Node* pNext = NULL;
Node* pTmp = NULL;
pCur = *pHead;
pTmp = pCur->next;
pCur->next = NULL;//表头变表尾
pNext = pTmp;
while(pNext){
pTmp = pNext->next;//因为要改变pNext->next指向,所以先保存起来
pNext->next = pCur;
pCur = pNext;
pNext = pTmp;
}
*pHead = pCur;//链表尾变链表头
return 0;
}
int destroySlist(Node** pHead){
Node* pCur = *pHead;
Node* pNext = pCur->next;
while(pNext){
if (pCur!=NULL)
free(pCur);
pCur = pNext;
pNext = pNext->next;
}
return 0;
}
void main() {
Node* p = NULL;
p= creatSList();
int pos = 0;
printSList(p);
printf("请输入插入位置:");
scanf("%d",&pos);
insertSlist(&p,pos);
printSList(p);
printf("请输入删除位置:");
scanf("%d",&pos);
deleteSList(&p,pos);
printSList(p);
printf("链表反转:\n");
reverseSList(&p);
printSList(p);
destroySlist(&p);
system("pause");
}
链表基本操作:增、删、反转
猜你喜欢
转载自blog.csdn.net/itswrj/article/details/88750604
今日推荐
周排行