题目:
画图解答:
方法:三指针
代码解答(带解析):
//题目给的结构体
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode ListNode;//重命名
ListNode* reverseList(ListNode* head) {
if(head==NULL)//判断链表是否为空
{
return NULL;
}
else if(head->next==NULL)//判断是否只有一个结点
{
return head;
}
ListNode* newhead=head->next;
ListNode* newtail=head;
ListNode* pcur=NULL;
while(newhead)
{
pcur=newhead;//pcur代替newnode站岗,防止newnode存储的地址丢失
newhead=newhead->next;//newnode走到pcur的前面,防止后面修改pcur->next存储的地址丢失
pcur->next=newtail;
newtail=pcur;
}
head->next=NULL;//这时候原来的头结点就是尾结点
return pcur;
}
完!!