# LeetCode206. Reverse Linked List（链表 / 模拟）

## 2019 年 01 月 26 日 • 阅读: 1028 • LeetCode • 阅读设置

• Easy
• Accepted：489,742
• Submissions：944,280

### Example

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

• 初始链表

• 初始指针

• 变化过程

### 代码

• Runtime: 4 ms, faster than 100.00% of C++ online submissions for Reverse Linked List.
/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* headNew = NULL; // 新链表表头
ListNode* tmp = NULL; // 临时指针
{
}
}
};

// 规范化写法

class Solution {
public:
ListNode* cur = head; // 当前节点
ListNode* headNew = NULL; // 新链表表头
while (cur != NULL)
{
ListNode* next = cur->next; // 后移
cur = next;
}
}
};


class Solution {
public:
}
};

### 测试

#include <bits/stdc++.h>
using namespace std;

// 链表节点
struct ListNode
{
int val;
ListNode * next;
ListNode(int x): val(x), next(NULL) {}
};

// 创建链表
{
if (n == 0)
return NULL;
for (int i = 1; i < n; ++i)
{
curNode->next = new ListNode(arr[i]);
curNode = curNode->next;
}
}

//打印链表
{
while (curNode != NULL)
{
cout << curNode->val << " -> ";
curNode = curNode->next;
}
cout << "NULL" << endl;
}

// 翻转链表
{
ListNode *cur = head; // 当前节点
ListNode *headNew = NULL; // 新链表表头
while (cur != NULL)
{
ListNode *next = cur->next; // 后移
cur = next;
}
}

// 删除链表
{
while (curNode != NULL)
{
ListNode* delNode = curNode;
curNode = curNode->next;
delete  delNode;
}
}

int main()
{
int n = 6;
int arr[10];
for (int i = 0; i < n; ++i)
arr[i] = rand() % 20 ;
}