题解 | #反转链表#

反转链表

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
		stack<int> s;
		ListNode *p = new ListNode(0);
		p = pHead;
		while (p!=nullptr) {
			s.push(p->val);
			p = p->next;
		}
		if(s.empty()) return NULL;
		pHead->val = s.top();
		s.pop();
		p = pHead;
		while (!s.empty()) {
			ListNode *temp = new ListNode(0);
			temp->val = s.top();
			s.pop();
			p->next = temp;
			p = temp;
		}
		return pHead;
    }
};

全部评论

相关推荐

求你们别卷了的卡尔很想拿:骑手也算hc,当然6000+
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务