版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BruceYan63/article/details/79168182
35.翻转链表
题目
翻转一个链表
样例
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
解题思路
定义三个指针记录指针走向.
注意要避免 Core Dumped. 要想到头指针为空和节点数为两个的情况
参考代码
class Solution {
public:
/*
* @param head: n
* @return: The new head of reversed linked list.
*/
ListNode * reverse(ListNode * head) {
if (head == NULL || head->next == NULL)
{
return head;
}
ListNode *p = head;
ListNode *q = head->next;
ListNode *r = q->next;
while(head->next != NULL)
{
head = head->next;
}
p->next = NULL;
while(q != NULL)
{
q->next = p;
p = q;
q = r;
if(r != NULL)
{
r = r->next;
}
}
return head;
}
};