单链表,双向链表实现逆序,C++代码,供大家参考。
一般Node用struct定义,我这用的class.
void reverseList_main()为主函数。
class Node {
public:
int m_value;
Node *next;
//构造函数
Node(int value);
};
Node::Node(int value)
{
m_value = value;
}
class doubleNode {
public:
int m_value;
doubleNode *next;
doubleNode *last;
doubleNode(int value);
};
doubleNode::doubleNode(int value)
{
m_value = value;
}
void printLinkedList(Node *head)
{
while (head != nullptr)
{
cout << "head.value= " << head->m_value <<endl;
head = head->next;
}
}
void printDLinkedList(doubleNode* head)
{
while (head != nullptr)
{
cout << "head.value= " << head->m_value << endl;
head = head->next;
}
}
// 后往前 next head1 pre
Node* reverseList(Node* head) {
Node* pre = nullptr;
Node* next = nullptr;
while (head!= nullptr) {
next = head->next;
head->next = pre;
pre = head;
head = next;
}
return pre;
}
doubleNode* reverseDList(doubleNode * head)
{
doubleNode* pre = nullptr;
doubleNode* next = nullptr;
while (head != nullptr) {
next = head->next;
head->next = pre;
head->last = next;
pre = head;
head = next;
}
return pre;
}
//主函数
void reverseList_main()
{
cout << "reverseList *************" << endl;
Node* pnode1 = new Node(7);
Node* pnode2 = new Node(8);
Node* pnode3 = new Node(9);
Node* pnode4 = new Node(10);
pnode1->next = pnode2;
pnode1->next->next = pnode3;
pnode1->next->next->next = pnode4;
printLinkedList(pnode1);
Node* rcp=reverseList(pnode1);
printLinkedList(rcp);
cout << "reverseDList *************" << endl;
doubleNode* pDnode1 = new doubleNode(11);
doubleNode* pDnode2 = new doubleNode(22);
doubleNode* pDnode3 = new doubleNode(33);
doubleNode* pDnode4 = new doubleNode(44);
pDnode1->next = pDnode2;
pDnode1->next->next = pDnode3;
pDnode1->next->next->next = pDnode4;
printDLinkedList(pDnode1);
doubleNode* rcdp = reverseDList(pDnode1);
printDLinkedList(rcdp);
delete pnode1 ;
delete pnode2 ;
delete pnode3 ;
delete pnode4 ;
delete pDnode1;
delete pDnode2;
delete pDnode3;
delete pDnode4;
}