c语言实现:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* pre = NULL;
struct ListNode* p = head;
struct ListNode* next;
while(p)
{
next = p->next;
p->next = pre;
pre = p;
p = next;
}
return pre;
}
用一个栈将链表节点逆序,没有必要,徒增加了空间复杂度。 因为是单链表,没有办法直接找到前驱,所以需要两个指针;