链表的结构
<pre name="code" class="html"><pre name="code" class="cpp">struct listnode { int data; listnode *next; };
分析:
1)若链表为空或只有一个元素,则直接返回;
2)设置两个前后相邻的指针p,q,将p所指向的节点作为q指向节点的后继;
3)向后移动,重复2),知道q为空;
4)调整链表头和链表尾。
实现代码如下:
#include "iostream" using namespace std; struct ListNode { int data; ListNode *next; }; void prt_linked_list(ListNode* head); ListNode* reverse_linked_list(ListNode* head); void main() { ListNode *head; head=new ListNode; head->data=-1; head->next=NULL; int x; cin>>x; ListNode *p,*q; p=head; while(x!=-1) { q=new ListNode; q->data=x; q->next=NULL; p->next=q; p=q; cin>>x; } prt_linked_list(head); head=reverse_linked_list(head); prt_linked_list(head); } void prt_linked_list(ListNode* head) { ListNode *p; p=head->next; while(p!=NULL) { cout<<p->data; cout<<" "; p=p->next; } } ListNode* reverse_linked_list(ListNode* head) { ListNode *p,*q; ListNode *t = NULL; p=head; if (p->next==NULL||p->next->next==NULL) { return head; } p=head->next; q=head->next->next; while(q!=NULL) { t=q->next; q->next=p; p=q; q=t; } head->next->next=NULL; head->next=p; return head; }