问题:已知一个单链表,将这个单链表反转过来,并返回反转之后的单链表。
思想:使用头插法的思想,将原本单链表中的数据反转,即每次插入数据的时候,不是将数据放到链表的末尾而是放到链表的头部。
代码如下:
ListNode* ReverseLists(ListNode* l) {
ListNode *newList = new ListNode();
newList->next=NULL;
ListNode *p=l;
ListNode *pNext;
while(p->next!=NULL){
pNext=p->next;
p->next=newList->next;
newList->next=p;
p=pNext;
}
return newList;
}
完整的代码如下:
#include <iostream>
using namespace std;
//定义链表的结构
struct ListNode {
int val;
ListNode *next;
ListNode() {}
ListNode(int x) : val(x), next(NULL) {}
};
//反转链表
//方法一,使用头插法的思想获取。
ListNode* ReverseLists(ListNode* l) {
ListNode *newList = new ListNode();
newList->next=NULL;
ListNode *p=l;
ListNode *pNext;
while(p->next!=NULL){
pNext=p->next;
p->next=newList->next;
newList->next=p;
p=pNext;
}
return newList;
}
//将数据添加到LNode中
void AddLNode(ListNode* head,int x){
ListNode* pNew = new ListNode();
pNew->next=NULL;
pNew->val=x;
if(head==NULL)
head=pNew;
else{
ListNode *temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=pNew;
}
}
// 打印LNode中的数据
void printLnode(ListNode* head){
ListNode *p=head;
while(p!=NULL){
cout<<p->val<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
/*
//也可以通过这种方式添加数据到链表中,但是有点low,所以下面采取了定义一个函数AddLNode()的形式。
ListNode* head=new ListNode(1);
ListNode* node2=new ListNode(7);
ListNode* node3=new ListNode(13);
ListNode* node4=new ListNode(4);
ListNode* node5=new ListNode(5);
head->next=node2;
node2->next=node3;
node3->next=node4;
node4->next=node5;
node5->next=NULL;
*/
ListNode* head=new ListNode(1);
AddLNode(head,12);
AddLNode(head,4);
AddLNode(head,14);
AddLNode(head,32);
cout<<"反转之前:"<<endl;
printLnode(head);
ListNode* rear=ReverseLists(head);
cout<<"反转之后:"<<endl;
printLnode(rear);
return 0;
}