目录
题目描述:
解题思路1:定义新链表+头插
定义指针cur指向旧链表头结点,next保存下一个结点的地址。
创建链表新的头结点指针,并且指向空,
改变结点1下一个指针的指向,让其指向新的头结点
更新新链表头结点指针,一直遍历迭代,当cur为空遍历结束。
代码实现:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* newhead=NULL;
struct ListNode* cur=head;
struct ListNode* next=NULL;
while(cur)
{
next=cur->next;
//头插方法
cur->next=newhead;
newhead=cur;
cur=next;
}
return newhead;
}
解题思路2:颠倒原链表指针指向
定义三个结点指针n1,n2,n3 ,三者迭代遍历,结束条件为n2=NULL。
迭代遍历
开始:n1=NULL n2指向结点1,n3指向结点2
迭代:n1=n2 n2=n3 n3=n3->next
结束: n1指向原链表的尾结点即反转链表的头结点 n2=NULL
代码实现:
struct ListNode* reverseList(struct ListNode* head){
//指针顺序交换
if(head==NULL)
return NULL;//注意空链表
struct ListNode* n1=NULL;
struct ListNode* n2=head;
struct ListNode* n3=NULL;
n3=n2->next;
// 顺序颠倒
while(n2)
{
//倒指向
n2->next=n1;
//迭代
n1=n2;
n2=n3;
//n3为空就不需要next了
if(n3)
n3=n3->next;
}
return n1;
}