链表的基本操作

来源:互联网 发布:linux用户修改默认目录 编辑:程序博客网 时间:2024/06/11 22:53

之前看到了一个博客里写了各类关于链表的基本操作,感觉好屌。因为作为c语言的初学者,指针就很难理解,何况各种倒腾指针的链表。最近灵光焕发,突然理解了链表,于是这里把我自己写的链表基本操作贴上。

其实说是灵光焕发,实际上是,只要理解了指针和结构体,也就自然而然的理解了链表。节点无非是一个普普通通的结构体,链表的一切操作,无非是用指针来对这个结构体来做操作。


#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int ElemType;


typedef struct Node{
ElemType elem;
Node * next;
}Node,*pNode;


//创建一个节点,需要头节点指针,元素值,本函数没有直接用途,主要为了创建链表方便点
void creatNode(pNode head,ElemType k){
pNode p1=(pNode)malloc(sizeof(Node));
memset(p1,0,sizeof(Node));
(*p1).elem=k;
(*p1).next=(*head).next;
(*head).next=p1;
}


//创建一个链表,需要头节点
void creatLink(pNode head){
ElemType k=0,j=0;
printf("Do you want another node ? [0/1] ");
scanf ("%d",&k);
while (k==1){
printf("input the value of the node ");
scanf("%d",&j);
creatNode(head, j);
printf("Do you want another node ? [0/1] ");
scanf ("%d",&k);
}
}


//打印链表
void printLink(pNode head){
pNode p;
p=head;
while ((*p).next!=NULL){
printf ("%d---->",(*p).elem);
p=(*p).next; 
}
printf (" #%d# \n",(*p).elem);


}


//在第k个元素之后插入元素x
void insertNode(pNode head){
int k=0,x=0,l=0;
pNode p,p1;
printf("\nDo you want to insert anything? [1/0]");
scanf("%d",&l);
if (l!=1)
goto w;
printf ("\nwhere do you want to insert ?");
scanf ("%d",&k);
printf ("\ninput the value of the node :");
scanf ("%d",&x);


p1=(pNode)malloc(sizeof(Node));
memset(p1,0,sizeof(Node));
(*p1).elem=x;
p=head;
for (int i=0;i<k;i++){
p=(*p).next;
}
(*p1).next=(*p).next;
(*p).next=p1;


w: k=0;
}


//删了第k个元素
ElemType delNode(pNode head){
int k=0,l=0;
pNode p,q,r;
p=head,q=head,r=head;


printf ("\nDo you want to delete anything? [1/0] ");
scanf ("%d",&l);
if (l!=1)
goto w;


printf ("\n which node do you want to delete? ");
scanf ("%d",&k);


for (int i=1;i<k;i++){
p=(*p).next;
q=(*p).next;
}
r=(*p).next;
(*p).next=(*q).next;
l=(*r).elem;
free(r);
printf ("\nyou delete %d \n",l);
return l;


w: return 0;
}


//求表长,不包括头节点
int LinkLength(pNode head){
int i=0;
pNode p;
p=head;
if((*p).next==NULL)
goto w;
while ((*p).next!=NULL){
i++;
p=(*p).next;
}
return i;
w: return 0;
}


//
int _tmain(int argc, _TCHAR* argv[])
{
pNode head; //在main里创建一个头节点,之后的一切操作都是针对头结点的

head=(pNode)malloc(sizeof(Node));
memset(head,0,sizeof(Node));

creatLink(head);
printLink(head);


insertNode(head);
printLink(head);


delNode(head);
printLink(head);


printf ("\nNow the length of this link is %d ",LinkLength(head));


system("pause");




return 0;
}

0 0
原创粉丝点击