1.删除一个无头单链表的非尾节点 2.从尾到头打印单链表

来源:互联网 发布:敖龙女 捏脸数据 ff14 编辑:程序博客网 时间:2024/05/22 14:17

1.删除一个无头单链表的非尾节点


这里主要是采用数据替换,将需要删除的节点的下一个结点放在需要删除结点的位置,依次将需要删除结点的后续结点前移,即可完成删除。

void DeleteNotTail(pNode pos){pNode cur = pos->_next;assert(pos->_next);          //数据替换pos->_data = pos->_next->_data;pos->_next = pos->_next->_next;}

 2.从尾到头打印单链表 

主要有两种方法:

(1)非递归实现:

若只有一个结点或没有结点直接返回,有多个结点时需要逆置。

void PrintfReverseNon(pList* pplist)     //非递归实现{pList cur = *pplist;pList newList = NULL;assert(pplist);if ((*pplist == NULL) || ((*pplist)->_next == NULL)){return;}while (cur){pNode tmp = cur;cur = cur->_next;tmp->_next = newList;newList = tmp;}*pplist = newList;}

(2)递归实现

同样,没有结点直接返回,有多个结点时,找第一个节点的下一个结点,直到找到该链表的最后一个结点,打印出该节点的数据,相当于栈,先将数据一次放入栈中,直到所有的数据完全放入,再一次弹出栈,即可完成逆置。

void PrintfReverse(pList plist)        //递归实现{pNode cur = plist;if (cur==NULL){return;}if (cur->_next){PrintfReverse(cur->_next);}printf(" %d\n",cur->_data);}

完整代码:

#include #include #include typedef int DataType;typedef struct ListNode{DataType _data;struct ListNode* _next;}Node,*pNode,*pList;void Init(pList* pplist){assert(pplist);*pplist = NULL;}pNode BuyNode(DataType x){pNode pnode = (pNode)malloc(sizeof(Node));if (pnode == NULL){perror("malloc");return NULL;}pnode->_data = x;pnode->_next = NULL;return pnode;}void Push(pList* pplist,DataType x){pNode NewNode = BuyNode(x);if (*pplist == NULL){*pplist = NewNode;}else{pNode cur = *pplist;while (cur->_next){cur = cur->_next;}cur->_next = NewNode;}}pNode Find(pList plist,DataType x){if (plist == NULL){return NULL;}else{pNode cur = plist;while (cur){if (cur->_data == x){return cur;}cur = cur->_next;}return NULL;}}void DeleteNotTail(pNode pos){pNode cur = pos->_next;assert(pos->_next);          //数据替换pos->_data = pos->_next->_data;pos->_next = pos->_next->_next;}void PrintfReverseNon(pList* pplist)     //非递归实现{pList cur = *pplist;pList newList = NULL;assert(pplist);if ((*pplist == NULL) || ((*pplist)->_next == NULL)){return;}while (cur){pNode tmp = cur;cur = cur->_next;tmp->_next = newList;newList = tmp;}*pplist = newList;}void PrintfReverse(pList plist)        //递归实现{pNode cur = plist;if (cur==NULL){return;}if (cur->_next){PrintfReverse(cur->_next);}printf(" %d\n",cur->_data);}void Printf(pList plist){pNode cur = plist;while (cur){printf(" %d", cur->_data);cur = cur->_next;}printf(" NULL\n");}void Test(){pList plist;Init(&plist);Push(&plist, 1);Push(&plist, 2);Push(&plist, 3);Push(&plist, 4);Push(&plist, 5);Printf(plist);pNode ret = NULL;ret = Find(plist, 4);/*if (ret != NULL){printf("找到了\n");}else{printf("没找到\n");}*/DeleteNotTail(ret);Printf(plist);PrintfReverse(plist);PrintfReverseNon(&plist);Printf(plist);}

阅读全文
0 0