问题很简单:反转一个链表。
其实就是对链表的基础操作,思路是顺着链表头结点的next指针遍历整个链表。假设链表前三个节点分别为A、B、C。
1.A->next = C;
2.B->next = A;
以A的next节点作为判断依据即可遍历整个链表并实现前后两个节点的指针反转。虽然思路很简单,但写的时候发现C的快忘得差不多了,为了复习C我在C++工程中完全以C的代码实现的。诸如new方法我用malloc方法替换手动为结构体分配堆内存等。并不影响程序运行,代码如下:
#include<iostream>
using namespace std;
typedef struct Node {
int data;
struct Node * next;
}Node;
//生成一个节点
struct Node* CreateNode(){
struct Node * node = (struct Node*)malloc(sizeof(struct Node));
node->next = NULL;
return node;
}
//构建一个链表
void CreateNodeTable(struct Node * start){
start->data = 0;
struct Node * preNode = start;
struct Node * thisNode;
for (int i = 1; i < 10; i++) {
thisNode = CreateNode();
thisNode->data = i;
preNode->next = thisNode;
preNode = thisNode;
}
}
//打印一个链表
void PrintNodeTable(struct Node * start) {
struct Node * temp = start;
while (temp -> next != NULL)
{
cout << temp->data;
temp = temp->next;
}
cout << temp->data;
cout << endl;
}
//翻转一个链表
struct Node * ReverseNodeTable(struct Node * start) {
struct Node * preNode = start;
struct Node * thisNode = start;
while (start -> next != NULL)
{
thisNode = start->next;
start->next = start->next->next;
thisNode->next = preNode;
preNode = thisNode;
}
return thisNode;
}
int main() {
struct Node * start = CreateNode();
CreateNodeTable(start);
PrintNodeTable(start);
struct Node * newStart = ReverseNodeTable(start);
PrintNodeTable(newStart);
//防止秒退死循环
while (1)
{
}
}
显然时间复杂度仅为O(n),空间复杂度是常数级的复杂度。