对于带头结点的单链表的相关操作

来源:互联网 发布:opencv 匹配优化 编辑:程序博客网 时间:2024/06/05 16:52
#include <stdio.h>#include <string.h>#include <stdlib.h>struct node{int data;                                                          //数据域struct node *next;   //指针域};struct node *create_node(int num){struct node *p = (struct node*)malloc(sizeof(struct node));if(p == NULL){printf("malloc error!\n");return NULL;}bzero(p,sizeof(struct node));                                     //清空p->data = num;p->next = NULL;return p;}void insert_tail(struct node *head,struct node *new){struct node *p = head;while(p->next != NULL){p = p->next;}p->next = new;//new->next = NULL;}void insert_head(struct node *head,struct node *new){new->next = head->next;head->next = new;}void display(struct  node *head){struct node *p = head;while(p->next != NULL){p = p->next;printf("%d\n",p->data);//p = p->next;}}void insert_middle(struct node *head,int num,struct node *new){int flag = 0;struct node *p = head;struct node *pre = NULL;while(p->next != NULL){pre = (struct node*)malloc(sizeof(struct node));pre->data = new->data;p = p->next;if(p->data == num){pre->next = p->next;p->next = pre;p = p->next;free(pre);}}if(flag == 0){printf("no find!insert error!\n");}}int reserve_link(struct node *head){if((head->next == NULL)||(head->next->next == NULL)){printf("reserve error!\n");return -1;}struct node *ptr1 = head->next;struct node *ptr2 = ptr1->next;struct node *ptr3 = ptr2->next;while(ptr3 != NULL){ptr2->next = ptr1;ptr1 = ptr2;ptr2 = ptr3;ptr3 = ptr3->next;}ptr2->next = ptr1;head->next->next = NULL;head->next = ptr2;}int delete_node(struct node *head,int num){struct node *p = head;struct node *pre = NULL;while(p->next != NULL){pre = p;p = p->next;if(p->data == num){/*if(p->next == NULL){pre->next = NULL;free(p);p = NULL;return 0;}*///else//{pre->next = p->next;free(p);p = NULL;   return 0;//}}}printf("delete error!\n");}int main(){struct node *head = create_node(0);//struct node *head = NULL;/*insert_tail(head,create_node(1));insert_tail(head,create_node(2));insert_tail(head,create_node(3));printf("node1:%d\n",head->next->data);printf("node2:%d\n",head->next->next->data);printf("node3:%d\n",head->next->next->next->data);*/struct node *temp = NULL;int i = 0;for(i = 0;i < 5;i++){temp = (struct node*)malloc(sizeof(struct node));temp->data = i+1;//insert_tail(head,temp);insert_head(head,temp);}temp = (struct node*)malloc(sizeof(struct node));temp->data = 3;insert_head(head,temp);display(head);printf("插入后的结果:\n");struct node *new = (struct node*)malloc(sizeof(struct node));new->data = 18;insert_middle(head,1,new);display(head);/*printf("删除后的结果:\n");delete_node(head,18);display(head);*/printf("逆序后的结果:\n");reserve_link(head);display(head);return 0;}

关于逆序的相关操作详解:

http://www.360doc.com/content/16/0323/10/26211242_544530084.shtml【转】

原创粉丝点击