单链表常见操作

来源:互联网 发布:em算法图像分割 编辑:程序博客网 时间:2024/06/04 23:35
编译环境:VS2008#include<stdio.h>#include<stdlib.h>typedef char DataType;typedef struct ListNode{DataType data;struct ListNode * next;}ListNode, * LinkList;/*创建一个空的带头结点的链表*/LinkList createList(){LinkList head;head = (ListNode *)malloc(sizeof(ListNode));if(!head)return NULL;head->next = NULL;return head;}/*创建一个非空的链表,头插法*/int createListByHead(LinkList &head){//这里用的是引用head = (ListNode *)malloc(sizeof(ListNode));if(!head)return -1;head->next = NULL;ListNode *p = head;char ch;while((ch=getchar())!='\n'){p = (ListNode *)malloc(sizeof(ListNode));p->data = ch;p->next = head->next;head->next = p;}return 1;}/*头插法建立链表,返回链表的头指针*/LinkList createListBYHead1(){LinkList head = createList();LinkList p;char ch;while((ch=getchar())!='\n'){p = (ListNode *)malloc(sizeof(ListNode));p->data = ch;p->next = head->next;head->next = p;}return head;}/*添加节点*/int add(LinkList &head,DataType value){ListNode *p = head;while(p->next){p = p->next;}LinkList insertNode = (ListNode *)malloc(sizeof(ListNode));insertNode->data = value;insertNode->next = p->next;p->next = insertNode;return 1;}/*return node by location*/LinkList get(LinkList &head,int location){ListNode *p = head;for(int i=0;i<location;i++){if(!p->next)return NULL;p = p->next;}return p;}int del(LinkList &head,int location){ListNode *p = head;if(location<1)return -1;for(int i=0;i<location-1;i++){//将p移到要删除节点的前驱if(p->next==NULL)return -1;//位置不合法p = p->next;}/*删除节点不存在,有可能删除节点的前驱存在,但要删除节点位置的前驱为终端节点是也不合法*/if(p->next)return -1;ListNode *q = p->next;//if(q->next==NULL)//如果要删除的节点是最后一个节点{free(q);p->next = NULL;}else{p->next = q->next;free(q);}return 1;}void printList(LinkList &head){ListNode *p = head;while(p->next){p = p->next;//printf("%c",p->data);putchar(p->data);putchar(' ');}}

0 0
原创粉丝点击