#include<iostream> #define ElemType int using namespace std; typedef struct Node { ElemType data; struct Node *next; }; void Create(Node *&l) { //尾插法 int x; l->next = NULL; //头结点 Node *s,*r = l; //r为表尾指针 cin >> x; while (x != -1) { s = new Node; s->data = x; r->next = s; r = s; cin >> x; } r->next = NULL; } void Print(Node *&l) { //输出链表中的数据 Node *p = l->next; while (p != NULL) { cout << p->data << " "; p = p->next; } cout << endl; } void Delete(Node *&l) { //单链表的删除操作 Node *p = l; Node *q = l->next; //保存后继指针,防止断链 while (p!= NULL ) { delete p; p = q; if (q != NULL) { q = q->next; } } } void Inverse(Node *&l) { //采用头插法 Node *p = NULL, *r = NULL; //对于空间复杂度为O(1),切记防止断链 p = l->next; l->next = NULL; //新建只有头结点的链表 while (p != NULL) { r = p->next; //保存后继指针 p->next = l->next; l->next = p; p = r; } } int main() { Node *l = new Node; //新建结点,并且创建指针 Create(l); Print(l); Inverse(l); Print(l); Delete(l); //释放内存 system("pause"); return 0; } /* 12 43 56 67 34 32 12 65 -1 */
C++单链表逆置
猜你喜欢
转载自blog.csdn.net/coolsunxu/article/details/80139364
今日推荐
周排行