翻转一个单向链表的c语言代码

# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>

typedef struct Node
{
 int data;
 struct Node * pNext;
}NODE, * PNODE;

PNODE creat_list(void);
void traverse_list(PNODE pHead);
PNODE ReverseList(PNODE pHead);

int main(void)
{
 PNODE pHead = NULL;
 PNODE pH = NULL;
 
 pHead = creat_list();
 traverse_list(pHead);
 
 printf("The reverse list is:\n");
 pH = ReverseList(pHead);
 traverse_list(pH);
 
 
 return 0;
}

PNODE creat_list(void)
{
 int len;
 int i;
 int val;
 
 PNODE pHead = (PNODE)malloc(sizeof(NODE));
 if(NULL == pHead)
 {
  printf("内存分配失败,程序终止!\n");
  exit(-1);
 }
 PNODE pTail = pHead;
 pTail->pNext = NULL;
 
 printf("请输入您要生成的链表节点的个数:len = ");
 scanf("%d", &len);
 
 for(i=0; i<len; ++i)
 {
  printf("请输入第%d个节点的值:", i+1);
  scanf("%d", &val);
  
  PNODE pNew = (PNODE)malloc(sizeof(NODE));
  if(NULL == pNew)
  {
   printf("内存分配失败,程序终止!\n");
   exit(-1);
  }
  pNew->data = val;
  pTail->pNext = pNew;
  pNew->pNext = NULL;
  pTail = pNew;
 }
 return pHead;
}

void traverse_list(PNODE pHead)
{
 PNODE p = pHead->pNext;
 while(NULL != p)
 {
  printf("%d ", p->data);
  p = p->pNext;
 }
 printf("\n");
}  

 

PNODE ReverseList(PNODE pHead)
{
 if(NULL == pHead)
  printf("empty");
 
 PNODE pre = NULL;
 PNODE cur = NULL;
 PNODE ne = NULL;
 PNODE firstNode = NULL;
 
 pre = pHead->pNext;
 cur = pre->pNext;
 firstNode = pre;
 
 while(cur)
 {
  ne = cur->pNext;
  cur->pNext = pre;
  pre = cur;
  cur = ne;
 }
 firstNode->pNext = NULL;
 pHead->pNext = pre;
 
 return pHead;
}

你可能感兴趣的:(c,list,struct,null,语言,include)