链表测试用例-翻转链表

#include<vector>
using namespace std;

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


ListNode* reverse(ListNode* head) {
	ListNode* pre = NULL;
	ListNode* cur = head;
	while (cur) {
		ListNode* t = cur->next;
		cur->next = pre;
		pre = cur;
		cur = t;
	}
	return pre;
}



int main() {
	ListNode* h1 = new ListNode(1);
	ListNode* h2 = new ListNode(2);
	ListNode* h3 = new ListNode(3);
	ListNode* h4 = new ListNode(4);
	ListNode* h5 = new ListNode(5);

	h1->next = h2;
	h2->next = h3;
	h3->next = h4;
	h4->next = h5;
	h5->next = NULL;

	ListNode* res = reverse(h1);
	while (res) {
		cout << res->val;
		res = res->next;
	}

	return 0;
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务