欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单向链表的反转

程序员文章站 2024-03-21 14:19:16
...
#include <iostream>
#include <list>
#include <vector>

using namespace std;

class ListNode {
public:
	ListNode *next;
	int data;
};

ListNode* reverse(ListNode * head) {

	ListNode *pCur, *pPrev, *pNext;

	pPrev = NULL;
	pCur = head;

	while (pCur != NULL) {
		pNext = pCur->next;
		pCur->next = pPrev;
		pPrev = pCur;
		pCur = pNext;
	}

	return pPrev;
}

void travelList(ListNode* head) {
	ListNode *cur = head;
	while (cur != NULL) {
		cout << "node: " << cur->data << endl;
		cur = cur->next;
	}
}

int main() {

	ListNode *head = NULL, *cur = NULL;

	for (int i = 0; i < 10; i++) {
		ListNode * temp = new ListNode;
		temp->data = i;
		temp->next = NULL;
		if (cur == NULL) {
			cur = temp;
			head = temp;
		} else {
			cur->next = temp;
			cur = temp;
		}
	}

	cout << "beafore reverse:" << endl;
	travelList(head);
	cout << "================== end =================" << endl;

	cout << "after reverse:" << endl;
	cur = reverse(head);
	travelList(cur);
	cout << "================== end =================" << endl;

	vector<int> testV;
	list<int> testL;

	return 0;
}