反转链表
题目描述:反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
题解思路:利用就地逆置的方法,将原链表头指针置空,依次读取链表结点,然后利用头插法插入原链表,要注意没有头结点的操作。
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* p,*q;
p=head;
int flag=0;
while(p)
{
q=p;
p=p->next;
if(!flag)
{
q->next=NULL;
flag=1;
}
else
{
q->next=head;
}
head=q;
}
return head;
}
迭代方法:设置pre和cur指针分别指向前驱结点和当前结点,保存当前结点的next指针,然后将cur的next指针指向前驱结点pre即可,最后返回pre指针。
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* pre,*cur,*temp;
pre=NULL;
cur=head;
while(cur)
{
temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
return pre;
}