今天笔试的一个题目,贴出来一方面是为了总结,也希望表大家有点帮助。单链表的反转算法就是将链表依次取出来建一个新的链表,新插入的结点在链表的最前面。
#include <iostream>
using namespace std;
struct NODE{
int data;
NODE * next;
};
NODE* createList(int len) {
NODE *head = NULL;
NODE *tail = NULL;
for (int i = 0; i < len; i++) {
NODE *newNode = new NODE;
newNode->data = i;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
NODE* reverseList(NODE *head) {
if (head == NULL || head->next == NULL)
return head;
NODE *newHead = NULL;
NODE *temp = NULL;
while(head != NULL) {
temp = head;
head = head->next;
temp->next = newHead;
newHead = temp;
}
return newHead;
}
void print(NODE *head) {
cout << "the list is:" << endl;
while (head) {
cout << head->data << endl;
head = head->next;
}
}
int main() {
NODE *head = createList(10);
print(head);
head = reverseList(head);
print(head);
return 0;
}