链表逆序的实现方法


typedef struct Node{
       char iElement;
       Node* pNext;
};

typedef struct Link{
       Node* pHead;
       int iLinkSize;
};

Link* initLink()
{
      Link* pLink = (Link*)malloc(sizeof(Link));
      if (NULL == pLink)
      {
            printf_s("链表初始化失败");
            return NULL;
      }
      pLink->pHead = NULL;
      pLink->iLinkSize = 0;
      return pLink;
}

void CreateLink(Link* pLink,int ele)
{
      Node* pNode = (Node*)malloc(sizeof(Node));
      if (NULL == pNode)
      {
            return;
      }
      pNode->iElement = ele;
      pNode->pNext = pLink->pHead;
      pLink->pHead = pNode;
      pLink->iLinkSize++;
}

void ShowLink(Link* pLink)
{
      if (NULL == pLink)
      {
            return;
      }
      Node* pNode = pLink->pHead;
      while (pNode)
      {
            printf_s("%c ",pNode->iElement);
            pNode = pNode->pNext;
      }
      printf_s("\n");
}

Link* ReLink(Link* pLink)
{
      Link* pTemp1= initLink();
      Link* pTemp2= initLink();
      pTemp1 = pLink;
      pLink = initLink();
      while(pTemp1->pHead)
      {
            pTemp2->pHead = pTemp1->pHead;
            pTemp1->pHead = pTemp1->pHead->pNext;
            pTemp2->pHead->pNext = pLink->pHead;
            pLink->pHead = pTemp2->pHead;
      }
      return pLink;
}
int main()
{
       Link* pLink = initLink();
       char iEle;
       cin>>iEle;
       while (iEle != '#')
       {
             CreateLink(pLink,iEle);
             cin>>iEle;
       }
       ShowLink(pLink);
       Link* pReLink = ReLink(pLink);
       ShowLink(pReLink);
       free(pLink);
       return 0;
}

运行结果:

简单点的算法试下如下:

Link* ResLink(Link* pHead)
{
      Link* pLink1,pLink2;
      pLink1 = pHead;
      pHead = NULL;
      while (pLink1)
      {
            pLink2 = pLink1;
            pLink1 = pLink1->next;
            pLink2->next = pHead;
            pHead = pLink2;
      }
      return pHead;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值