您的位置:首页 > 编程语言 > C语言/C++

C语言反转单链表

2016-06-15 15:24 323 查看

1、反转单链表

        定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。链表结点定义如下:

        struct node //结点类型定义

        {

                int val; //结点的数据域

                struct node *pNext;//结点的指针域(存放结点的直接后继的地址

      };

2、链表的结点结构

┌───┬───┐

│data
│next │

└───┴───┘

data域 -- 存放结点值的数据域

next域 -- 存放结点的直接后继的地址(位置)的指针域(链域)

[cpp]
view plain
copy





#include <stdio.h>  
#include <stdlib.h>  
  
struct node  
{  
    int val;  
    struct node *pNext;  
};  
  
struct node *gen()  
{  
    struct node *pHead = NULL;  
    printf("反转前::");
    for(int i = 10; i > 0; i--){  
// 创建了一个空节点并分配内存,此时此节点还没有数据,为空节点
        struct node * p = (struct node *)malloc(sizeof(struct node)); 
       //在空节点的data域赋值
        p -> val = i;  
       //因为pHead初始化时为NULL,第一次for循环表示是第一个节点(后面无其他节点),p->pNext的下个节点为NULL空
        p -> pNext = pHead;  
        //将已填充好的第一次分配的节点p赋值给pHead,此时pHead不为空,以此循环翻转链表
        pHead = p;  
        printf("%d ",i);
    }     
        printf("\n");

    return pHead;  
}  
  
void display(struct node *pHead)  
{  
    printf("反转后::");
    while( pHead != NULL)  
    {     
        printf("%d ", pHead->val);  
        pHead = pHead->pNext;  
    }     
    printf("\n");  
}  
  
//递归实现  
struct node * reverse(struct node *pHead)  
{  
    if (pHead == NULL || pHead -> pNext == NULL)  
    {     
        return pHead;  
    }     
    struct node *p = pHead -> pNext;  
    struct node *pNewHead =  reverse(p);  
    p -> pNext = pHead;  
    pHead ->pNext = NULL;  
    return pNewHead;  
}  
  
//尾递归实现  
struct node * do_reverse_tail(struct node *pHead, struct node *pNewHead)  
{  
    if(pHead == NULL)  
    {  
        return pNewHead;  
    }  
    else  
    {  
        struct node *pNext = pHead->pNext;  
        pHead->pNext = pNewHead;  
        return do_reverse_tail(pNext, pHead);  
    }  
}  
  
struct node * reverse_tail(struct node *pHead)  
{  
    return do_reverse_tail(pHead, NULL);  
}  
  
//迭代实现  
struct node * reverse_it(struct node *pHead)  
{  
    struct node *pNewHead = NULL;  
    struct node *pPrev = NULL;  
    struct node *pCur = pHead;  
    while(pCur != NULL)  
    {  
        struct node *pTmp = pCur->pNext;  
        if(pTmp == NULL)  
        {  
            pNewHead = pCur;  
        }  
        pCur->pNext = pPrev;  
        pPrev = pCur;  
        pCur = pTmp;  
    }  
  
    return pNewHead;  
}  
  
int main()  
{  
    struct node *pHead = gen();  
    display(pHead);  
    pHead = reverse_it(pHead);  
    display(pHead);  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: