单链表逆转

List结构定义如下:

struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
}

L是给定单链表,函数Reverse要返回被逆转后的链表。

实现:

ListNode* ReverseList(ListNode* pHead) {
        if(pHead==NULL||pHead->next==NULL) 
            return pHead;//如果链表为空或者链表中只有一个元素
         
        ListNode* pNode=pHead;//当前指针
        ListNode* pReversedHead=NULL;//新链表的头指针
        ListNode* pPrev=NULL;//当前指针的前一个结点
         
        while(pNode!=NULL){//当前结点不为空时才执行
            ListNode* pNext=pNode->next;//链断开之前一定要保存断开位置后边的结点
             
            if(pNext==NULL)//当pNext为空时,说明当前结点为尾节点
                pReversedHead=pNode;
            
            pNode->next=pPrev;//指针反转
            pPrev=pNode;
            pNode=pNext;
        }
        return pReversedHead;
        /*   递归
        //如果链表为空或者链表中只有一个元素
        if(pHead==NULL||pHead->next==NULL) return pHead;
        //先反转后面的链表,走到链表的末端结点
        ListNode* pReverseNode=ReverseList(pHead->next);
        //再将当前节点设置为后面节点的后续节点
        pHead->next->next=pHead;
        pHead->next=NULL;
        return pReverseNode;
        */
        /*栈操作
        if(pHead==NULL||pHead->next == NULL)
            return pHead;
        ListNode * p=pHead;
        ListNode * newHead;
        stack<ListNode *> stack1;
        while(p->next!=NULL)
        {
            stack1.push(p);
            p=p->next;
        }
        newHead = p;
        while(!stack1.empty())
        {
          p->next=stack1.top();
            p=p->next;
            stack1.pop();
        }
        p->next=NULL;
        return newHead;
        */
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值