#include <stdio.h>
#include <malloc.h>
struct node
{
int data;
struct node *m_pNext;
};
typedef struct node * PNode;//PNode相当于node*
/*递归版
PNode reverseList(PNode head)
{
if(head == NULL || head->m_pNext == NULL)
return head;
PNode newHead = reverseList(head->m_pNext);
head->m_pNext->m_pNext = head;
head->m_pNext=NULL;
return newHead;
}
*/
//非递归版
PNode reverseList(PNode head)
{
if( (head == NULL) || (head->m_pNext == NULL))
{
return head;
}
PNode cur = head;
PNode pre = NULL;
while(cur != NULL)
{
PNode pNext = cur->m_pNext;
cur->m_pNext = pre;
pre = cur;
cur = pNext;
}
//cur->m_pNext = pre;
return pre;
}
PNode CreateList(const int num)
{
PNode head = NULL,p = NULL,q = NULL;
for(int i = 1;i <= num; i ++)
{
p = (PNode)malloc(sizeof(struct node));
p->data = i;
if(NULL == head)
{
head = p;
}
else
{
q->m_pNext = p;
}
q = p;
}
p->m_pNext = NULL;
return head;
}
int main()
{
PNode head = CreateList(5);
PNode newHead = reverseList(head);
PNode p = newHead;
while(NULL != p)
{
printf("%3d",p->data);
p = p->m_pNext;
}
return 0;
}
单链表的逆置
最新推荐文章于 2021-05-21 18:27:09 发布