【Leetcode刷题】--链表--第206题 单链表的翻转

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值