剑指offer--1.删除链表中某个节点 2.从尾到头打印链表

来源:互联网 发布:李荣浩2017新专辑知乎 编辑:程序博客网 时间:2024/06/04 00:53
#include<stdio.h>#include<assert.h>#include<malloc.h>struct ListNode{int data;struct ListNode* next;};
//创建链表void CreatListNode(struct ListNode** phead, int data){struct ListNode* pnew=malloc(sizeof(struct ListNode));pnew->data=data;pnew->next=NULL;if(*phead==NULL) //空链表*phead=pnew; //phead是一个指向指针的指针,每次保存头节点的地址else{struct ListNode* cur=*phead;while(cur->next!=NULL)//找到最后一个节点cur=cur->next;cur->next=pnew;}}
//回收链表void Destory(struct ListNode** phead){assert(phead);struct ListNode* cur=*phead;struct ListNode* del=NULL;while(cur){del=cur;cur=cur->next;free(del);}}
//从头到尾打印链表void Display(struct ListNode** phead){assert(phead);struct ListNode* cur=*phead;while(cur){printf("%d->",cur->data);cur=cur->next;}printf("NULL\n");}//删除某个含某值的节点void RemoveNode(struct ListNode** phead,int data){assert(phead);struct ListNode* cur=*phead;struct ListNode* prev=*phead;if(cur->data==data){*phead=cur->next;prev->next=NULL;free(prev);return;}while(cur){if(cur->data==data){prev->next=cur->next;    free(cur);cur->next=NULL;return;}else{prev=cur;cur=cur->next;}}}//递归的思想  从尾到头打印链表
//也可以用C++写调用库里的stackvoid printf_prevtoend(struct ListNode* cur){if(cur==NULL){return;}elseprintf_prevtoend(cur->next);printf("%d->",cur->data);}void PrintList_prevtoend(struct ListNode** phead){assert(phead);struct ListNode* cur=*phead;printf_prevtoend(cur);printf("NULL\n");}int main(){    struct ListNode* phead=NULL;    CreatListNode(&phead,1);    CreatListNode(&phead,2);    CreatListNode(&phead,3);    CreatListNode(&phead,4);    CreatListNode(&phead,5);    Display(&phead);    //RemoveNode(&phead,1);    PrintList_prevtoend(&phead);    //Display(&phead);    Destory(&phead);}

1 0
原创粉丝点击