题目描述
输入一个链表,反转链表后,输出新链表的表头。
提交代码:
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if (pHead==NULL)
{
return NULL;
}
ListNode* p_head = pHead;
ListNode* p_fast = p_head->next;
pHead->next = NULL; //指向null,细节
while (p_fast !=NULL)
{
ListNode* temp = p_fast->next;
p_fast->next = p_head;
p_head=p_fast;
p_fast = temp;
}
return p_head;
}
};
测试案列:
int main()
{
Solution *s = new Solution();
//vector<int> v = { 2,4,6,1,3,5,7 };
ListNode *l1 = new ListNode(1);
ListNode *l2 = new ListNode(2);
ListNode *l3 = new ListNode(3);
ListNode *l4 = new ListNode(4);
ListNode *l5 = new ListNode(5);
ListNode *l6 = new ListNode(6);
ListNode *l7 = new ListNode(7);
l1->next = l2;
l2->next = l3;
l3->next = l4;
l4->next = l5;
l5->next = l6;
l6->next = l7;
ListNode* out_list =s->ReverseList(l1);
system("pause");
return 0;
}
结果: