反转链表-C语言实现

来源:互联网 发布:学生体质监测数据上报 编辑:程序博客网 时间:2024/05/16 15:05

题目要求:在O(n)的时间内反转链表,并返回反转后链表的头指针。

分析:求解链表问题首先一定要考虑非空问题,而且要注意终止的位置。

                                                

如图所示,反转的时候定义三个节点,pCur代表当前节点、pNext代表指向的下一个节点、pPre代表前一个节点。有了这三个节点就可以从前往后遍历,而且保证链表不会断裂!

#include<stdio.h>#include<stdlib.h>struct ListNode{int value;ListNode* next;};ListNode* reverseList(ListNode* head){ListNode* pCur=head;ListNode* rHead=NULL;ListNode* pPre=NULL;while(pCur!=NULL){ListNode* pNext=pCur->next;if(pNext==NULL)rHead=pCur;pCur->next=pPre;pPre=pCur;pCur=pNext;}return rHead;}int main(){int n;while(scanf("%d",&n)!=EOF){ListNode* head=(ListNode *)malloc(sizeof(ListNode));ListNode* p=head;p->next=NULL;for(int i=0;i<n;i++){ListNode* q=(ListNode*)malloc(sizeof(ListNode));int tmp;scanf("%d",&tmp);q->value=tmp;p->next=q;p=q;p->next=NULL;}ListNode *pHead=reverseList(head->next);while(pHead){printf("%d ",pHead->value);pHead=pHead->next;}}return 0;}

1 0
原创粉丝点击