设计一个算法,通过遍历一趟,将链表中所有结点的链接方向逆转,仍利用原表的存储空间。
#include <iostream>
using namespace std;typedef int Elemtype;
#define ERROR 0;
#define OK 1;typedef struct LNode
{Elemtype data; //结点保存的数据struct LNode* next; //结构体指针
}LNode, * LinkList;/*单链表初始化*/
bool Init_LinkList(LinkList& L)
{L = (LinkList)malloc(sizeof(LNode)); //新建头结点if (L == NULL){return ERROR;}L->data = 0;L->next = NULL;return OK;
}/*单链表头插法*/
bool LinkList_head_instert(LinkList& L)
{int x = 0;LNode* p = NULL;while (cin >> x){p = (LinkList)malloc(sizeof(LNode));if (p != NULL) //防止分配地址失败{p->data = x;p->next = L->next;L->next = p;if (cin.get() == '\n') break; //检测换行符}else{exit(0);cout << "内存分配失败" << endl;}}return OK;
}/*单链表尾插法*/
bool LinkList_tail_instert(LinkList& L)
{int x = 0;LNode* p = NULL;LNode* r = NULL;r = L;while (cin >> x){p = (LinkList)malloc(sizeof(LNode));if (p != NULL) //防止分配地址失败{p->data = x;p->next = NULL;r->next = p;r = p;if (cin.get() == '\n') break; //检测换行符}else{exit(0);cout << "内存分配失败" << endl;}}return OK;
}/*单链表遍历*/
bool LinkList_All_value(LinkList L)
{if (L->next == NULL){cout << "链表为空" << endl;return ERROR;}LNode* s = NULL;s = L->next;while (s != NULL){cout << s->data << " ";s = s->next;}cout << endl;free(s);return OK;
}/*单链表长度*/
int LinkList_length(LinkList L)
{int count = 0;LNode* s = NULL;s = L->next;while (s != NULL){count++;s = s->next;}return count;
}/*清空单链表*/
void Clear_LinkList(LinkList& L)
{LNode* p = L->next;LNode* q = NULL;while (p != NULL){q = p->next;free(p);p = q;}L->next = NULL;
}/*销毁单链表*/
void Destory_LinkList(LinkList& L)
{LNode* p = NULL;LNode* q = NULL;p = L;while (p != NULL){q = p->next;free(p);p = q;}L = NULL;
}
//--------------------------------------核心代码--------------------------------------//
bool reverse(LinkList& A) //头插法
{LNode* pa = NULL;LNode* q = NULL;pa = A->next;A->next = NULL;if (pa == NULL){cout << "单链表数据为空!!!" << endl;return ERROR;}while (pa != NULL){q = pa->next;pa->next = A->next;A->next = pa;pa = q;}return OK;
}//--------------------------------------核心代码--------------------------------------//
//设计一个算法,通过遍历一趟,将链表中所有结点的链接方向逆转,仍利用原表的存储空间。int main(void)
{LinkList A = NULL;Init_LinkList(A);LinkList_tail_instert(A);//test1: 1 2 3 100 5 6 8LinkList_All_value(A);reverse(A);//逆转单链表LinkList_All_value(A);return 0;
}