链表操作

来源:互联网 发布:电脑编程语言 编辑:程序博客网 时间:2024/06/08 15:26
#include <stdio.h>#include <malloc.h> /*                                                    链表节点的定义:*/struct node{int data;//节点内容node *next;//下一个节点};//创建单链表(带有头结点) struct node *create(){int i=0;//链表中数据个数node *head,*p,*q;int x=0;head=(node*)malloc(sizeof(node));//创建头结点while(1){printf("please input the data: (0 end)");  scanf("%d",&x); if(0 == x)                          break;    //输入0结束p=(node*)malloc(sizeof(node));p->data=x;if(++i==1){head->next=p;//连接到head的后面}else{q->next=p;//连接到链表尾端}q=p;}q->next=NULL;//链表的最后一个指针为NULLreturn head;}/*                                                   编程实现单链表的测长:返回单链表的长度*/int length(node *head){int len=0;node *p;p=head->next;while(p!=NULL){len++;p=p->next;}return len;}//实现单链表的打印void print(node *head){node *p;int index=0;if(head->next==NULL)//链表为空{printf("link is empty\n");return;}p=head->next;while(p!=NULL){printf("the %dth node is:%d\n",++index,p->data);p=p->next;}}/*                                              单链表节点的查找查找单链表pos位置的节点,返回节点指针pos从0开始,0返回head节点*/struct node *search_node(node *head,int pos){node *p=head->next;if(pos<0){printf("incorrect position to search node!\n");return NULL;}if(pos==0){return head;}if(p==NULL){printf("Link is empty\n");return NULL;}while(--pos){if((p=p->next)==NULL){printf("incorrect position to search node\n");break; //超出链表返回}}return p;}/*                                      单链表节点的插入在单链表中某位置(pos个节点)后面插入节点1.插入到链表首部2.插入到链表中间3.插入到蓝标尾部单链表某个位置插入节点,返回链头指针,pos从0开始计算,0表示插入到head节点后面*/struct node *insert_node(node *head,int pos,int data){node *item=NULL;node *p;item=(node *)malloc(sizeof(node));item->data=data;if(pos==0)//插入到链表头后面{head->next=item;//return head;}p=search_node(head,pos);//获得pos的节点指针if(p!=NULL){item->next=p->next;p->next=item;}return head;}/*                                   单链表节点的删除删除单链表pos位置的节点,返回头指针pos从开始计算,1表示删除head后面的第一个节点*/struct node *delete_node(node *head,int pos){node *item=NULL;node *p=head->next;if(p==NULL){printf("link is empty\n");return NULL;}p=search_node(head,pos-1);//获得pos-1位置的节点指针if(p!=NULL && p->next!=NULL){item=p->next;p->next=item->next;delete item;}return head;} /*                                       将单链表逆序单链表的逆置遍历一遍单链表,利用一个辅助指针存储遍历过程中当前指针指向下一个元素,然后将当前元素的指针反转,利用已经存储的指针往后继续遍历*/struct node *reverse(node *head){node *p,*q,*r;if(head->next==NULL)//链表为空{return head;}p=head->next;q=p->next;//保存原第二个节点p->next=NULL;//原第一个节点为末节点while(q!=NULL)//遍历各个节点的next指针反转{r=q->next;//记录剩下的链表q->next=p;p=q;q=r;}head->next=p;//新的第一个节点为原末节点return head;}int main(){node *head=create();//创建单链表printf("Length:%d\n",length(head));//测单链表的长度head = insert_node(head,2,5);//在第二个节点的后面添加5printf("在第二个节点的后面添加5:\n");print(head);//打印单链表head = delete_node(head,2);//删除第二个节点printf("删除第二个节点:\n");print(head);printf("将该链表逆序:\n"); reverse(head);print(head);return 0;}

0 0
原创粉丝点击