单链表的几个基本操作
生活随笔
收集整理的這篇文章主要介紹了
单链表的几个基本操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*以頭插法,創建長度為n的單鏈表,并實現對其的增、刪、改、查*/
?
#include<stdio.h> #include<stdlib.h>struct node {int data;struct node *next; };struct node *Creat_List(struct node *head, int n) //創建鏈表 {struct node *p;for(int i=0;i<n;i++){p = (struct node *)malloc(sizeof(struct node));scanf("%d",&p->data);p->next = head;head = p;}return head; }void Put(struct node *head) //打印鏈表 {struct node *p;p = head;while(p != NULL){printf("%d ",p->data);p = p->next;}printf("\n"); }struct node* Insert(struct node *head,int k,int num) //在k處增加元素num {struct node *p;p = head;for(int i=0;i<k;i++){p = p->next;}struct node *temp;temp = (struct node *)malloc(sizeof(struct node));temp->data = num;temp->next = p->next;p->next = temp;return head; }struct node *Delete(struct node *head, int k) {struct node *p;p = head;for(int i=1;i<k-1;i++){p = p->next;}struct node *temp;temp = p->next;p->next = temp->next;return head; }bool Find(struct node *head,int num) {struct node *p;p = head;while(p != NULL){if(p->data == num){return true;}p = p->next;}return false; }struct node *Change(struct node *head,int k,int num) //將數字k改為num {struct node *p;p = head;while(p!=NULL){if(p->data == k){p->data = num;}p = p->next;}return head; }int main() {int n; //鏈表長度scanf("%d",&n);struct node *head=NULL;head = Creat_List(head, n);Put(head);head = Insert(head,2,1000);//Put(head);head = Delete(head,4);//Put(head);head = Change(head,4,6);//Put(head);bool ok = Find(head,7);if(ok)printf("yes\n");elseprintf("no\n");return 0; } View Code?
轉載于:https://www.cnblogs.com/alan-W/p/5887002.html
總結
以上是生活随笔為你收集整理的单链表的几个基本操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ajax-典型应用-验证用户名
- 下一篇: hihocoder 网络流二·最大流最小