链表原地反转
链表头节点有数据。否则反转后头结点有数据,而尾节点没有数据。
思路很简单:
假如原来的链表是:1->2->3->4->5->null
第一个节点插入第二个节点之后:2->1->3->4->5->null
再将2->1当做整体插入3之后:3->2->1->4->5->null
.
.
.
最后得到5->4->3->2->1->null
返回结果的头结点指针
复杂度是O(n)
ListNode* reverse(ListNode *head)//链表原地反转
{
ListNode *tail = head;
ListNode *p = head;
while (tail->next!=NULL)
{
p = head;
head = tail->next;
tail->next = head->next;
head->next = p;
}
return head;
}