首页 > 代码库 > 有头结点的链表操作
有头结点的链表操作
#include<iostream>#include <stack>using namespace std;struct Node{ int data; Node *next;};//没有头结点的插入新节点Node* AddNode(Node *head,int num)//如果是void 类型的 那么head要用指向指针的指针{ Node *pNew=(Node*)malloc(sizeof(Node)); pNew->data=http://www.mamicode.com/num; pNew->next=NULL; if (head==NULL) { head=pNew; } else { Node *pCur=head; while(pCur->next!=NULL) { pCur=pCur->next; } pCur->next=pNew; } return head;}//链表无头结点 要删除某个值为val的节点Node* DeleNode(Node *head,int val){ if (head==NULL) { return NULL; } Node *ptobeDelete=NULL; if (head->data=http://www.mamicode.com/=val)//如果删除的是头结点 { ptobeDelete=head; head=head->next; } else { Node *pcur=head; while(pcur->next!=NULL&&val!=pcur->next->data)//注意条件判断 { pcur=pcur->next; } if (pcur->next!=NULL&&pcur->next->data=http://www.mamicode.com/=val)//找到了的话 注意判断条件 { ptobeDelete=pcur->next; pcur->next=pcur->next->next; } } if (ptobeDelete!=NULL)//有可能找不到 所以要判断是否为空 { delete ptobeDelete; ptobeDelete=NULL; } return head;}//逆序打印不含头结点的链表 头文件为stackvoid ReversPrintList(Node *head){ Node *pcur=head; stack<Node*>nodes; while (pcur!=NULL)//这条语句包含了判断首节点是否为空 { nodes.push(pcur); pcur=pcur->next; } while(!nodes.empty()) { pcur=nodes.top();//访问栈顶元素 cout<<pcur->data<<endl; nodes.pop(); }}//递归方式逆序打印void ReversPrintListByRecurs(Node *head){ if (head!=NULL) { if (head->next!=NULL) { ReversPrintListByRecurs(head->next);//先打印后面的节点 } cout<<head->data<<endl;//再打印前面的节点 }}
有头结点的链表操作
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。