您的位置:首页 > 编程语言 > C语言/C++

C++笔试题之实现单链表反转

2018-02-01 15:39 633 查看
链表反转在面试中经常容易被问及,比如:

输入 1 2 3 4 5 6 7 8 9 10
输出 10 9 8 7 6 5 4 3 2 1

#include <iostream>
using namespace std;

struct Node{
int data;
Node* next;
};

void Display(Node *head)// 打印链表
{
if (head == NULL)
{
cout << "the list is empty" << endl;
return;
}
else
{
Node *p = head;
while (p)
{
cout << p->data << " ";
p = p->next;
}
}
cout << endl;
}

Node* ReverseList(Node* head)// 反转链表
{
if (head == NULL)
return NULL;

Node* cur = head;
Node* pre = NULL;
Node* nex = NULL;
while (cur->next != NULL)
{
nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
cur->next = pre;
return cur;
}

Node* Init(int num) // 创建链表
{
if (num <= 0)
return NULL;
Node* cur = NULL;
Node* head = NULL;
Node* node = (Node*)malloc(sizeof(Node));
node->data = 1;
head = cur = node;
for (int i = 1; i < num; i++)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = i + 1;
cur->next = node;
cur = node;
}
cur->next = NULL;
return head;
}

int main( )
{
Node* list = NULL;
list = Init(10);
Display(list);
Node* newlist = ReverseList(list);
Display(newlist);

system("pause");
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息