单链表的就地逆置

回溯

关注

阅读 81

2022-02-16

题目
单链表的就地逆置

思路
链表的头插法

代码

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        
        ListNode* p=nullptr;
        ListNode* q=pHead;
        ListNode* temp=nullptr;
        
        while(q){
            temp=q->next;   // 暂存q的下一个
            q->next=p; // 新节点的下一个是动态指针
            p=q;      // 动态指针前移
            q=temp;
        }
        
        return p;
    }
};

精彩评论(0)

0 0 举报