C++實現鏈表逆序

鏈表的結構

<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;
}


發佈了33 篇原創文章 · 獲贊 15 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章