单链表逆置

上一篇文章

这个之前有过类似的一道题目。手写,基础。可以改变链表结构的为Reverse(),不可改变的使用DFS;

#include <iostream>
using namespace std;
typedef struct node{
    int data;
    node *next;
}node;
 
node *Create(){
    node *head = new node;
    node *p;
    for( int i = 0; i < 10; ++i ){
        node *q = new node;
        q -> data = i;
        if( head -> data == 0 )
            head -> next = q;
        else{
            p -> next = q;
 
        }
        p = q;
        head -> data++;
    }
    p -> next = NULL;
    return head;
}
 
void Print( node *head ){
    node *p = head -> next;
    while( p != NULL ){
        cout << p -> data <<endl;
        p = p -> next;
    }
}
 
node *Reverse( node *head ){
    node *p = head -> next;
    node *q = p -> next;
    node *r;
    p -> next = NULL;
    while( q != NULL ){
        r = q -> next;
        q -> next = p;
        p = q;
        q = r;
    }
    head -> next = p;
    return head;
}
 
void Dfs( node *head ){
    node *p = head -> next;
    if( p != NULL ){
        if( p -> next != NULL )
            Dfs( p );
        cout << p -> data << endl;
    }
}
int main()
{
    node *Head = Create();
    Print( Head );
    Dfs( Head );
    return 0;
}

bo-jwolf

一级美术,二级策划,三级程序

留下你的评论

*评论支持代码高亮<pre class="prettyprint linenums">代码</pre>

相关推荐