2.LeetCode第206题 单链表的翻转
这道题和剑指offer的第3题从尾到头打印链表是有区别的。单链表的反转是对结点一个一个操作的,每次把后面的一个结点抛到前面,不需要开辟另外的内存空间。
使用C++和Python实现:
/**
* 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) {
if(head==NULL)
return NULL;
//结点初始化
ListNode *pCur,*pPre,*pNext;
pPre=head;
pCur=pPre->next;
//翻转链表
while(pCur){
pNext=pCur->next;
pCur->next=pPre;
pPre=pCur;
pCur=pNext;
}
//返回头指针
head->next=NULL;
head=pPre;
return head;
}
};
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
p=head
pCur=None
pPre=None
while p is not None:
pCur=p.next
p.next=pPre
pPre=p
p=pCur
return pPre