代码题--C++--反转链表

代码题--C++--反转链表


题目描述

输入一个链表,反转链表后,输出新链表的表头。

解题思路:

    (1)if(head!=NULL)保存头的下一个结点为p,
    (2)当前head结点的next置为head的头结点
    (3)head的前结点置为head
    (4)head置为p(head的next),继续循环

注意:一定要初始化结点。

代码如下:

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* p = NULL;//初始化必须为NULL,存放pHead的下一个
        ListNode* pre = NULL;//初始化必须为NULL,存放pHead的pre
        if(pHead == NULL)
            return NULL;
        while(pHead != NULL)
        {
           p = pHead->next;    //指针倒指
           pHead->next = pre; 
           
           pre = pHead;//实现循环
           pHead = p;
        }
        return pre;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41103495/article/details/108835291
今日推荐