反转链表(牛客网)

解题思路:

(1)看了别人的都是设了多个指针,理解费力,哈哈哈

(2)我就把它保存下来,反过来设置结点

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
    	if (pHead==NULL) return pHead;
		stack<ListNode*> s;
		while(pHead) {
			s.push(pHead);
			pHead = pHead->next;
		}
		ListNode *pre = s.top(),*head = s.top();
		s.pop();
		while(!s.empty()) {
			pre->next = s.top();
			pre = s.top();
			s.pop();
		}
		pre->next=NULL;
		return head;
    }
};
发布了302 篇原创文章 · 获赞 277 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105609589