描述
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
数据范围: 0≤n≤1000
要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:
示例1
输入: {1,2,3}
返回值: {3,2,1}
示例2
输入: {}
返回值: {}
说明: 空链表则输出空
思路:
一、迭代法
遍历链表,将当前链表的下一个指针指向前面一个节点。但是有一个问题:头节点没有前驱节点,因此设置一个虚拟节点。
代码
#include<iostream>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode(int x=0):val(x),next(NULL){}
};
ListNode* createList()
{
int a = 0;
ListNode* dummy = new ListNode();
ListNode* tail = dummy;
ListNode* temp = NULL;
while (true)
{
cin >> a;
temp = new ListNode(a);
tail->next = temp;
tail = tail->next;
if (cin.get() == '\n')
break;
}
return dummy->next;
}
void printList(ListNode* head)
{
ListNode* out = head;
while (out != NULL)
{
cout << out->val << ',';
out = out->next;
}
}
//采用遍历方式进行反转
ListNode* reverseList(ListNode* head)
{
ListNode* pre = NULL;
ListNode* cur = head;
while (cur != NULL)
{
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
int main()
{
while (true)
{
ListNode* head = createList();
ListNode* result = reverseList(head);
printList(result);
}
return 0;
}