leecode:206 翻转链表
参考资料: leecode题解C++实现
一: 链表基本构成
1、链表由链表节点(data)和指向下一个节点的指针(next)构成。
2、代码构成
typedef struct LIST {
int data;//节点
LIST* next;//指向下一节点指针
}List,*list_it;
二:创建链表
根据题目选择尾插法建立链表,回车(\n)结束输入
void creat_it(list_it p) {
int x;
List* s, * r = p;
char mark = 's';//记录是否结束输入
while (cin >> x) {
s = (List*)malloc(sizeof(List));
s->data = x;
r->next = s;
r = s; //换绑指针到 s 因此没有影响到p
mark = getchar();
if (mark == '\n') break;
}
r->next = NULL;
}
三:翻转链表(非递归)
List* Stir(List*head) {
List* a;
List* prev = NULL;
while (head) {
a = head->next;
head->next = prev;
prev = head;
head=a;
}
return prev;
}
要点:近似 头插法 逐个扫描链表中的节点
四:完整代码
#include<iostream>
using namespace std;
typedef struct LIST {
int data;
LIST* next;
}List,*list_it;
//尾插法创建链表
void creat_it(list_it p) {
int x;
List* s, * r = p;
char mark = 's';
while (cin >> x ) {
s = (List*)malloc(sizeof(List));
s->data = x;
r->next = s;
r = s; //换绑指针到 s 因此没有影响到p
mark = getchar();
if (mark == '\n') break;
}
r->next = NULL;
}
//翻转链表 非递归算法
List* Stir(List*head) {
List* a;
List* prev = NULL;
while (head) {
a = head->next;
head->next = prev;
prev = head;
head=a;
}
return prev;
}
int main() {
List* p;
p = (List*)malloc(sizeof(List));
p->next = NULL;
creat_it(p);
List* b = Stir(p);
while (b->next != NULL) {
cout << b->data << " ";
b = b->next;
}
}