**反转链表**:
实现链表的逆置
最终将头节点转为尾节点,尾结点转为头节点
方法1:
n1,n2反转,n3迭代
struct ListNode *reverseList(struct ListNode* head)
{
if(head==NULL||head->next==NULL)
{
return head;
}
struct ListNode *n1=NULL,*n2=NULL,*n3=NULL;
n2=head;
n3=head->next;
while(n2!=NULL)
{
n2->next=n1;
n1=n2;
n2=n3;
if(n3)
{
n3=n3->next;
}
}
return n1;
}
方法2:
将原链表节点依次头插到新链表中,达到链表反转的效果
struct SListNode *reverseList(struct SListNode *head)
{
if(head==NULL||head->next=NULL)
{
return head;
}
struct SListNode *newhead=NULL;
struct SListNode *cur=head;
while(cur)
{
struct SListNode *next=cur->next;
cur->next=newhead;
newhead=cur;
cur=next;
}
return newhead;
}