输入一个链表的头结点,反转该链表,并返回反转后链表的头结点。
利用三个指针来翻转,代码如下
//翻转链表 #include<iostream> using namespace std; struct list{ int data; list* next; }; list* create_list(void){ list *current=new list; current->data=1; current->next=NULL; list *head=current; for(int i=2;i<=10;i++){ list * p=new list; p->data=i; p->next=NULL; current->next=p; current=p; } return head; } list* list_reverse(list *headNode){ list *node=headNode; list *last=NULL; //记录前面的已经翻转好的表头 list *reverse_head=NULL; //翻转后的表头 while(node){ list *link=node->next; if(!link) reverse_head=node; node->next=last; //利用三个指针翻转 last=node; node=link; //cout<<last->data<<endl; } return reverse_head; } void print(list *headNode){ while(headNode){ cout<<headNode->data<<" "; headNode=headNode->next; } cout<<endl; } int main(void){ list *head=create_list(); print(head); print(list_reverse(head)); system("pause"); return 0; }