C实现单链表

来源:互联网 发布:韩国申遗 知乎 编辑:程序博客网 时间:2024/04/29 14:41
typedef int DataType;typedef struct ListNode{DataType data;struct ListNode* next;}ListNode;//初始化链表void InitList(ListNode** pphead){*pphead = NULL;}//创建节点ListNode* BuyNode(DataType x){ListNode* tmp = (ListNode*)malloc(sizeof(ListNode));assert(tmp);tmp->data = x;tmp->next = NULL;return tmp;}//尾插void PushBack(ListNode** phead,DataType x){if(NULL == *phead){*phead = BuyNode(x);}else{ListNode* tial = *phead;while(tial->next != NULL){tial = tial->next;}tial->next = BuyNode(x);}}//打印void Print(ListNode* phead){ListNode* tmp = phead;while(tmp != NULL){printf("%d->",tmp->data);tmp = tmp->next;}printf("NULL");printf("\n");}//前插void PushFront(ListNode** phead,DataType x){if(*phead == NULL){*phead = BuyNode(x);}else{ListNode* tmp = BuyNode(x);tmp ->next = *phead;*phead = tmp;}}//尾删void PopBack(ListNode** phead){if(*phead == NULL){printf("kd");return;}else{ListNode* tmp = *phead;(*phead) = (*phead)->next;free(tmp);} }//找节点ListNode* Find(ListNode* phead,DataType x){if(NULL == phead){printf("KONG");return;}else{ListNode* cur = phead;while(cur){if(cur->data = x){return cur;}cur = cur->next;}return cur;}}//插入void Insert(ListNode* pos,DataType x){ListNode* tmp = BuyNode(x);tmp->next = pos->next;pos->next = tmp;}//翻转单链表ListNode* Reverse(ListNode* phead){ListNode* newhead = NULL;ListNode* tmp = phead;while(tmp){ListNode* cur = tmp;tmp = tmp->next;cur->next = newhead;newhead = cur;/*ListNode* cur = tmp->next;tmp->next = newhead;newhead = tmp;tmp = tmp->next;*/}return newhead;}//从尾到头打印单链表void printListFromTailToHead(ListNode* head)    {        if(head == NULL)            {            return;                      }      ListNode *newhead = NULL;        ListNode *cur = head;        while(cur)            {         ListNode *tmp = cur;            cur = cur->next;            tmp->next = newhead;            newhead = tmp;            }        ListNode *p = newhead;        while(p)            {            cout<<p->val<<endl;                p = p->next;                        }    }

1 0