~~~How can the writing style end in a dull way, and the story does not recognize ordinary at the beginning ✌✌✌
If you need the complete code, you can follow the public account below, and reply "code" in the background to get it. Aguang is looking forward to your visit~
Question:
Try to write an algorithm to reverse the singly linked list of the leading node in-place. The so-called "in-place" means that the auxiliary space complexity is O(1).
Problem solving ideas:
>头插法
Code:
#include <iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode *next;
} LNode, *LinkList;
// 头插法
void HeadInsert(LinkList &L)
{
int val = 0;
while (cin >> val)
{
LNode *s = new LNode;
s->data = val;
s->next = L->next;
L->next = s;
if (cin.get() == '\n')
{
break;
}
}
}
// 尾插法
void TailInsert(LinkList &L)
{
int val = 0;
LNode *r = L;
while (cin >> val)
{
LNode *s = new LNode;
s->data = val;
r->next = s;
r = s;
r->next = NULL;
if (cin.get() == '\n')
{
break;
}
}
}
// 遍历输出链表元素
void Print(LinkList L)
{
LNode *p = L->next;
while (p)
{
cout << p->data << '\t';
p = p->next;
}
cout << endl;
}
void fn(LinkList &L)
{
LNode *p, *r;
p = L->next;
L->next = NULL;
while (p)
{
r = p->next;
p->next = L->next;
L->next = p;
p = r;
}
}
int main()
{
LinkList L = new LNode;
TailInsert(L);
fn(L);
Print(L);
}