链表(一)链表的新建、反转、释放

来源:互联网 发布:淘宝销量少的可以买吗 编辑:程序博客网 时间:2024/05/22 16:38
#include <iostream>using namespace  std;//创建一个链表,释放链表的内存,将链表反转
//链表翻转需要三个指针:头 中 后typedef struct node{struct node *next;int num;}Node;Node * create(int num);void print(Node *head);void freeNode(Node *&head); //这里参数是指针的引用Node *inverse(Node *head);//如果不直接使用指针的引用的时候,函数体外的head并没置NULL,导致在print中引用了已经释放的变量;int main(){Node *head=create(15);print(head);print(inverse(head));freeNode(head);print(head);getchar();}Node * create(int num)//产生长度为num的链表{Node *head=new Node;head->num=0;Node *temp=head;for(int i=1;i<num;i++){temp->next=new Node;temp=temp->next;temp->num=i;}temp->next=NULL;return head;}// 释放head对应的链表,会每个节点的释放//类似于过河拆桥,从表头开始释放//对指针的释放只是把那块内存还给操作系统,指针中存的地址还是那块//因而要记得将指针重置NULL//参数是关于指针的引用 Node * &headvoid freeNode(Node *&head)  {if(head==NULL){return;}Node *temp=head;Node *tempNext=NULL;while (temp->next!=NULL){tempNext=temp->next;delete temp;temp=NULL;temp=tempNext;}delete temp;head=NULL;}void print(Node *head){if(head==NULL)return;Node *temp=head;while(temp->next!=NULL){cout<<temp->num<<"\t";temp=temp->next;}cout<<temp->num<<"\t";cout<<endl;}//单向链表逆转Node *inverse(Node *head){if(head==NULL||head->next==NULL){return head;//只有一个节点或者没有节点的情况}Node *temp=head;Node *tempNext=temp->next;Node *temp2=NULL;while(tempNext->next!=NULL)//找到倒数两个尾节点{//这里至少三个节点temp2=temp;temp=tempNext;tempNext=tempNext->next;temp->next=temp2;}tempNext->next=temp;head->next=NULL;//tempNext这是尾巴节点,即新的头结点return tempNext;}

0 0
原创粉丝点击