单向链表的反转

#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;
}

  

posted on 2013-11-01 20:02  DerDeath  阅读(470)  评论(0编辑  收藏  举报

导航

"); }); },1000); });