标签:blog io os sp for on 2014 log as
用一种算法来颠倒一个单链表的顺序,递归和非递归
#include <iostream> using namespace std; struct Node { int data; Node *next; }; Node* createLinkList(int a[], int n) { if(a == NULL || n == 0)return NULL; Node *L = NULL,*t = NULL; for(int i = 0; i < n; i++) { if( i == 0) { L = new Node; L->data = a[i]; L->next = NULL; t = L; } else { Node *s = new Node; s->data = a[i]; s->next = NULL; t->next = s; t = s; } } return L; } void showLinkList(const Node *L) { if( L == NULL)return; const Node *q = L; while(q != NULL) { cout << q->data << endl; q = q->next; } } Node* reverseLinkList(Node *L) { if( L == NULL)return NULL; if(L->next == NULL)return L; Node *p = reverseLinkList(L->next); L->next->next = L; L->next = NULL; return p; } Node* noRvseLinkList(Node *L) { if( L == NULL || L->next == NULL)return L; Node *p = L, *previous = NULL, *NextNode = NULL; while(p->next != NULL) { NextNode = p->next; //保存起下一个变量 p->next = previous; //将之前的node放在p->next previous = p; p = NextNode; } p->next = previous; return p; //return } int main() { int a[] = {1,2,3,4,5,6}; Node *L = createLinkList(a,6); showLinkList(L); cout << "-----------------------"<<endl; // L = reverseLinkList(L); L = noRvseLinkList(L); showLinkList(L); return 0; }
标签:blog io os sp for on 2014 log as
原文地址:http://blog.csdn.net/jiangge123456/article/details/41647821