C链表基础

来源:互联网 发布:淘宝网店装修软件 编辑:程序博客网 时间:2024/05/27 09:48
/*************************************************************************> File Name: list.c> Author: XXDK> Email: v.manstein@qq.com > Created Time: Tue 07 Mar 2017 02:36:16 AM PST ************************************************************************/#include<stdio.h>#include<stdlib.h>struct node {int data;struct node* next;};// 创建链表头结点struct node* create_list_head(void){struct node* head;head = (struct node*)malloc(sizeof(node));if(head == NULL) {printf("allocate memory failed: %s\n", __func__);return (struct node*)0;}head ->next = NULL;printf("head created ok.\n");return head;}// 头部插入链表结点int  insert_list_head(struct node* head, int data){struct node* temp;if(head == NULL) {printf("invalid list head: %s\n", __func__);}temp = (struct node*)malloc(sizeof(node));if(temp == NULL) {printf("allocate memory failed: %s\n", __func__);return -1;}temp->data = data;temp->next = head->next; // 新节点指针域指向head 的next节点head->next = temp; // 头节点的指针域指向tempreturn 0;}// 尾部插入链表节点int insert_list_tail(struct node* head, int data){struct node* temp;struct node* curr;if(head == NULL) {printf("invalid list head: %s\n", __func__);}temp = (struct node*)malloc(sizeof(node));if(temp == NULL) {printf("allocate memory failed: %s\n", __func__);return -1;}temp->data = data;temp->next = NULL;curr = head;while(curr->next) { // 寻找尾部节点位置curr = curr->next;}curr->next = temp; // 在其后插入return 0;}// 删除指定数据域的节点int delete_list_node(struct node* head, int data){struct node* curr = head->next;struct node* temp;struct node* prev = head;int flag = 0;if(head == NULL) {printf("invalid list head: %s\n", __func__);}while(curr) {if(curr->data == data) {printf("find a same data, delete now.\n");temp = curr;prev->next = curr->next;free(temp);flag = 1;}prev = prev->next;curr = curr->next;}if(!flag) {printf("same data not find.\n");}return 0;}//链表输出int print_list(struct node* head){struct node* curr = head->next;if(head == NULL) {printf("invalid list head: %s\n", __func__);}printf("list data: ");while(curr->next) {printf("[%d] ", curr->data);curr = curr->next;}printf("\n");return 0;}// 链表逆序(反转)// 思路:由头结点拿出第一个节点得到://包含头结点的一段链表A,//然后把剩下的链表B从头到尾,每拿出一个就用头插法,//插入A的头结点和第一个有效节点之间,从而达到逆序int reserve_list(struct node* head){struct node* lista = head;struct node* listb = head->next; struct node* temp;//1.将链表分为A,Blista->next = NULL;int i = 0;//printf("reserve\n");while(listb){//2.保存listb的第二个节点地址到temptemp = listb->next; //3.拿出listb节点插入lista头部listb->next = head->next;head->next = listb;//4.取listb的下一个节点(存储在temp中)继续listb = temp;}return 0;}int main(){struct node* list1, *list2;int a[] = {10, 20, 30, 40, 50, 60};list1 = create_list_head();list2 = create_list_head();for(int i = 0; i < sizeof(a)/sizeof(a[0]); i++){insert_list_head(list1, a[i]);insert_list_tail(list2, a[i]);}print_list(list1);print_list(list2);delete_list_node(list1, 30);print_list(list1);reserve_list(list2);print_list(list2);}

0 0
原创粉丝点击