链表基础(C语言实现)


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Node{
 int data;
 struct Node *next;

};
//创建带有头结点的单向链表
struct Node * SList_Creat() {
 int data=0;
 //创建头结点
 struct Node *head=NULL,*pm=NULL,*pCur=NULL;
 head = (struct Node*)malloc(sizeof(struct Node));
 if (head == NULL) {
  return NULL;
 }
 head->data = 0;
 head->next = NULL;
 //从键盘输入数据,创建业务结点
 printf("please enter the data of node(-1:quit)");
 scanf("%d", &data);
 //循环创建
 pCur = head;
 while (data != -1) {
  pm= (struct Node*)malloc(sizeof(struct Node));
  if (pm == NULL) { 
   return NULL;
  }
  pm->data = data;
  pm->next = NULL;
  pCur->next = pm;
  pCur = pCur->next;
  printf("please enter the data of node(-1:quit)");
  scanf("%d", &data);
 }
 return head;
 
}

//打印链表
int SLlist_Print(struct Node *head) {
 if (head == NULL) {
  return -1; 
 }
 struct Node *pm = NULL;
 pm = head->next;
 printf("\nBegin ");
 while (pm != NULL) {
  printf("%d ", pm->data);
  pm = pm->next;
 }
 printf("End\n");
}
//在值为x的节点前,插入值为y的值,若值为x的节点不存在,则插在表尾
int SLlist_NodeInsert(struct Node *head, int x, int y) { 
 int i = 1;
 if (head == NULL) {
  return -1;
 }
 struct Node *p1 = NULL,*p2=NULL, *tmp = NULL;
 tmp = (struct Node*)malloc(sizeof(struct Node));
 if (tmp == NULL) {
  return -1;
 }
 tmp->data = y;
 tmp->next = NULL;

 p1 = head;
 p2 = head->next;
 while (p2) {
  if (p2->data == x) {
   break;
  }
   p1 = p1->next;
   p2 = p2->next;
 }
   tmp->next = p2;
   p1->next = tmp;
 return 0;
}

//删除值为x的结点
int SLlist_NodeDel(struct Node *head, int x) {
 if (head == NULL) {
  return -1;
 }
 struct Node*p1 = NULL, *p2 = NULL;
 p1 = head;
 p2 = head->next;
 while (p2) {
  if (p2->data == x) {
   
   break;
  }
  p1 = p2;
  p2 = p2->next;
   
 }
 if (p2 == NULL) {
  printf("没有找到要删除的节点\n");
  return 0;
 }
 p1->next = p2->next;
 free(p2);
 return 0;
}

//销毁链表
int SLlist_Destory(struct Node*head) {
 if (head == NULL) {
  return -1;
 }
 struct Node *p = head,*tmp=NULL;
 while (p) {
  tmp = p->next;
  free(p);
  p = tmp;
 }
}

//链表逆置
int SList_Resve(struct Node *head) {
 if (head == NULL) {
  return -1;
 }
 struct Node *p=NULL, *q=NULL, *t=NULL;
 if (head->next == NULL || head->next->next == NULL) {
  return -2;
 }
 p = head->next;
 q = p->next;
 while (q != NULL) {
  //逆置之前把q的后继节点保存
  t = q->next;
  //逆置操作
  q->next = p;
  //前驱节点后移
  p = q;
  //逆置结点后移
  q = t; 
 }
 head->next->next = NULL;
 head->next = p;
 return 0;
}


void main() {
 struct Node *head = NULL;
 head = SList_Creat();
 SLlist_Print(head);
 
 SLlist_NodeInsert(head, 20, 19);
 SLlist_Print(head);
 SLlist_NodeDel(head, 20);
 SLlist_Print(head);
 SList_Resve(head);
 SLlist_Print(head);

 //SLlist_Destory(head);
 system("pause");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值