面试题16:反转链表
提交网址: http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168
或 https://leetcode.com/problems/reverse-linked-list/
Total Accepted: 101523 Total Submissions: 258623 Difficulty: Easy
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
- 参与人数:5517 时间限制:1秒 空间限制:32768K
- 本题知识点:链表
分析:
使用头插法,并每次将newhead获取到最前端临时结点(整体赋值)...
有空了,再来用递归思想实现一次...
AC代码:
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *p;
ListNode *newhead=NULL;
p=pHead;
if(pHead==NULL || pHead->next==NULL) return pHead;
while(p!=NULL)
{
ListNode *temp=p;
p=p->next;
temp->next=newhead; // 挂接上
newhead=temp; // 将新插入的节点整体复制给头指针结点
}
return newhead;
}
};