递归反序链表


 
int *p[10];     //包含指针的数组
int (*p)[10];   //指向数组的指针p[0]居然是一个数组int[10], 着实难以理解

struct stNode{
  stNode(int n){
    nValue = n;
    pNext=NULL;
  }
  int nValue;
  stNode* pNext;
};

//非递归
stNode* Reverse1(stNode* pN){
  if(pN == NULL|| pN->pNext == NULL){
    return pN;
  }
  stNode* pPre = pN;
  pN = pN->pNext;
  stNode* pNext = pN->pNext;

  pPre->pNext = NULL;
  while(pN->pNext != NULL){
    pN->pNext = pPre;
    pPre = pN;
    pN = pNext;
    pNext = pN->pNext;
  }
  pN->pNext = pPre;
  return pN;
}

//递归
stNode* Reverse2(stNode* pN){
  static stNode* pHead = pN;
  static stNode* pNewHead = NULL;
  if(pN==NULL){
    ;
  }else if(pN->pNext==NULL){
    pNewHead = pN;
  }else{
    stNode* pNew = Reverse(pN->pNext);
    pNew->pNext = pN;
  }

  if(pN == pHead){
    pHead->pNext = NULL;
    return pNewHead;
  }

  return pN;
}

int main() {
  stNode* pHead = new stNode(1);
  pHead->pNext = new stNode(2);
  pHead->pNext->pNext = new stNode(3);
  pHead->pNext->pNext->pNext = new stNode(4);

  stNode* pResult = Reverse2(pHead);

  return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值