单链表的反转问题

单链表反转问题经常会遇到。在此记录一下,以便查阅方便。

如果反转一个有头结点的使用下面的方法比较合适。

//反转单链表,此单链表带有头节点。//思想:使用tmp临时指针保存头结点与链表的关系typedefstructListNode{intdata;structListNode*next;}ListNode,*LinkList;voidReverseList(ListNode*Head){ListNode*current,*tmp;current=Head->next;if(current!=NULL)//反转后第一个节点的后继要为NULL{tmp=current;current=current->next;tmp->next=NULL;}while(current!=NULL){tmp=current;current=current->next;tmp->next=Head->next;Head->next=tmp;}}

如果没有头结点,下面的反转比较合适

//如果没有头节点,下面的函数比较适合//思想:使用pre和next两个指针来记录当前处理的节点的前一个节点和后一个节点的信息ListNode*ReverseLinkList(ListNode*head){ListNode*pre,*next;pre=NULL;next=NULL;while(head){next=head->next;head->next=pre;pre=head;head=next;}returnpre;}