在各大公司面试中,通常会遇到的最基本的算法题之一是单链表的倒序问题。在此仅介绍最常用的且复杂度相对较低的方法。
leetcode中同样也有这道题:Reverse a singly linked list
答案:http://www.programcreek.com/2014/05/leetcode-reverse-linked-list-java/
对于非递归的实现方法:使用三个临时指针依次遍历。
具体代码如下:
1. 首先给出节点类
1 class Node 2 { 3 public: 4 Node(string curData,Node *mNext){ 5 data = curData; 6 next = mNext; 7 } 8 ~Node(){ 9 cout<<data<<"析构函数"<<endl; 10 } 11 public: 12 string data; 13 Node *next; 14 15 };
2. 非递归实现单链表倒序:
Node *listInvert(Node *head) { Node *p1,*p2,*p3; p1 = head; p2 = p1->next; while(p2) { p3 = p2->next; p2->next = p1; p1 = p2; p2 = p3; } head->next = NULL;//注意:此时头指针改变 return p1; }
3. 递归实现逆序:
//递归调用 Node * reverseRecursion(Node *head) { if (head == NULL||head->next == NULL) { return head; } Node *second = head->next; head->next = NULL; Node *rest = reverseRecursion(second); second->next = head; return rest; }
4. 方法调用:
void printNode(Node *root) { while(root != NULL) { cout<<root->data<<" "; root = root->next; } cout<<endl; } int main(int argc, char const *argv[]) { Node *four = new Node("D",NULL); Node *third = new Node("C",four); Node *sec = new Node("B",third); Node *head = new Node("A",sec); // cout<<"原始链表顺序:"; // printNode(head); // Node *result = listInvert(head); // cout<<"倒序结果:"; // printNode(result); cout<<"原始链表顺序:"; printNode(head); Node *result = reverseRecursion(head); cout<<"递归 倒序结果:"; printNode(result); cout<<endl; delete head; delete sec; delete third; head = NULL; sec = NULL; third = NULL; return 0; }
5. 结果
原始链表顺序:A B C D
递归 倒序结果:D C B A
A析构函数
B析构函数
C析构函数
6. 源码 algorithm/list_invert.cpp