C++鏈表操作實(shí)際應(yīng)用技巧分享
作者:佚名
我們?cè)谶@里將會(huì)以一段代碼示例來(lái)為大家詳細(xì)講解有關(guān)C++鏈表操作的實(shí)現(xiàn)方法,希望大家可以從中掌握到其中的應(yīng)用技巧。
C++編程語(yǔ)言應(yīng)用范圍廣泛,在開(kāi)發(fā)人員眼中,它占據(jù)著非常重要的地位。在這里我們可以通過(guò)對(duì)C++鏈表操作的相關(guān)技巧,來(lái)充分了解一下這一語(yǔ)言的應(yīng)用方式以及他的應(yīng)用能給我們帶來(lái)哪些不同的感受。
C++鏈表操作代碼示例:
- // linklist.cpp : 定義控制臺(tái)應(yīng)用程序的入口點(diǎn)。
- #include "stdafx.h"
- #include "malloc.h"
- #include "stdlib.h"
- #define NULL 0
- #define LEN sizeof(struct student)
- struct student
- {
- long num;
- float score;
- struct student* next;
- };
- int n;
- struct student* creat()
- {
- struct student *head;
- struct student *p1,*p2;
- n=0;
- p1=p2=(struct student*)malloc(LEN);
- scanf("%ld",&p1->num);
- scanf("%f",&p1->score);
- head=NULL;
- while (p1->num!=0)
- {
- n++;
- if (n==1)
- {
- head=p1;
- }
- else
- {
- p2->next=p1;
- }
- p2=p1;
- p1=(struct student*)malloc(LEN);
- scanf("%ld",&p1->num);
- if (p1->num==0)
- break;
- scanf("%f",&p1->score);
- }
- p2->next=NULL;
- return (head);
- };
- void print(struct student *head)
- {
- struct student *p;
- printf("\n New,These %d records are:\n",n);
- p=head;
- if (head!=NULL)
- {
- do
- {
- printf("%d %5.1f\n",p->num,p->score);
- pp=p->next;
- }while (p!=NULL);
- }
- }
- struct student* insert(struct student *head,struct student *stud)
- {
- struct student *p0, *p1, *p2;
- p1=head;
- p0=stud;
- if (head==NULL)
- {
- head=p0;
- p0->next=NULL;//insert into head point
- }
- else
- {
- while ((p0->num>p1->num)&&(p1->next!=NULL))
- {
- p2=p1; //p2 is point to just p1 point to node;
- p1p1=p1->next;
- }
- if (p0->num<=p1->num)
- {
- if (p1==head)
- {
- head=p0;//insert into before first node
- }
- else
- {
- p2->next=p0;//insert into after point p2
- }
- p0->next=p1;
- }
- else
- {
- p1->next=p0; //insert into after last point
- p0->next=NULL;
- }
- }
- n++;
- return(head);
- };
- struct student* del(struct student *head,long num)
- {
- struct student *p1, *p2;
- if (head==NULL)
- {
- printf("\n list Null!\n");
- return (head);
- }
- p1=head;
- while (num!=p1->num&&p1->next!=NULL)
- //find num if equal p1->num
- {
- p2=p1;
- p1p1=p1->next;
- }
- if (num==p1->num)
- {
- if (p1==head)
- head=p1->next;//delete head node because num=head.num
- else
- p2->next=p1->next;//delete node. node is not head point
- printf("delete:%ld\n",num);
- n--;
- }
- else
- {
- printf("%ld not been found!\n",num);
- }
- return (head);
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- struct student *head,*end;
- head=creat();
- print(head);
- struct student insertnode;
- insertnode.num=3;
- insertnode.score=900;
- head=insert(head,&insertnode);
- print(head);
- head=del(head,3);
- print(head);
- return 0;
- }
C++鏈表操作的相關(guān)實(shí)現(xiàn)方法就為大家介紹到這里。
【編輯推薦】
責(zé)任編輯:曹凱
來(lái)源:
博客園