Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
/*//第一种新开辟了内存,并且运行时间较慢。 简单容易想
ListNode *key = NULL;
ListNode *temp;
while(head != NULL){
temp = (ListNode*)malloc(sizeof(ListNode));
temp->next = key;
temp->val = head->val;
key = temp;
head = head->next;
}
return key;*/
//第二种时间快,未占用内存,当然指针用了一点点。 指针方向翻转的思想
if(head == NULL ||head->next ==NULL)
return head;
ListNode *t,*p,*q;
t = head;
p = head->next;
t->next = NULL;
q = p;
while(q&&p){
q = p->next;
if(q){
p->next = t;
t = p;
p = q;
}
}
p->next = t;
return p;
}
};

本文介绍了一种使用迭代和递归两种方法反转单链表的算法。通过改变节点的next指针,实现链表的反转。提供了详细的代码实现,包括如何处理头节点、中间节点和尾节点,以及如何在不占用额外内存的情况下完成反转。
416

被折叠的 条评论
为什么被折叠?



