单链表逆置

本文介绍了一个简单的单链表实现,包括初始化、插入节点、打印链表及反转链表的功能。通过C语言代码示例展示了如何进行这些基本操作,并最终实现链表的反转。

#include "stdafx.h"
#include "malloc.h"
typedef struct node
{
   int data;
   struct node *next;
}nnode;

void initiate(nnode **head)
{
    *head=(nnode *)malloc(sizeof(nnode));
    (*head)->next=NULL;
}

void insert(nnode *head,int n)
{
    nnode *p=head;
    nnode *s;
    while(p->next!=NULL)
    {
        p=p->next;
    }
     s=(nnode *)malloc(sizeof(nnode));
     s->data=n;
     s->next=p->next;
     p->next=s;
}

void print(nnode *head)
{
   nnode *p=head->next;
   while(p!=NULL)
   {
       printf("%d ",p->data);
       p=p->next;
   }
}

void reverse(nnode *head)
{
    nnode *pre=head->next;
    nnode *tmp=pre->next;
    nnode *curr=tmp->next;
    pre->next=NULL;
    while(curr!=NULL)
    {
       tmp->next=pre;
       pre=tmp;
       tmp=curr;
       curr=curr->next;
    }
    tmp->next=pre;
    head->next=tmp;    
}
int main(int argc, char* argv[])
{ 
    nnode *head;
    initiate(&head);
    for(int i=0;i<10;i++)
    {
        insert(head,i+1);
    }

    /*打印单链表*/
    print(head);
    
    /*打印逆置后的单链表*/
    reverse(head);
    printf("\n打印逆置后的单链表\n");
    print(head);
    printf("Hello World!\n");
    return 0;
}

 

转载于:https://www.cnblogs.com/mrheyao/archive/2013/03/10/2952355.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值