这里用俩种方法解决
第一种方法,指针反转法
将
反转成
定义三个指针 n1=NULL,n2指向第一个节点,n3指向第三个节点.
反转的时候将n2指向n1,n2赋给n1,n3赋给n2,n3往后挪
终止条件为n2==NULL
返回n1
注意 当第二次的时候n3就已经为NULL了,第三次的时候n3已经为野指针。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL)
return NULL;
//起始条件
struct ListNode* n1=NULL;
struct ListNode* n2=head;
struct ListNode* n3=n2->next;
//终止条件
while(n2 != NULL)
{
n2->next=n1;
n1=n2;
n2=n3;
if(n3!=NULL)
n3=n3->next;
}
return n1;
}
第二种方法--头插法
新建一个空链表,将原链表的节点一个一个的插入。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
//存放第一个节点
struct ListNode* cur=head;
//新建一个新的链表用于存放
struct ListNode* newNode=NULL;
//终止条件 当cur为NULL时
while(cur!=NULL)
{
//用于存放第二个节点
struct ListNode* next=cur->next;
//头插第一个节点
cur->next=newNode;
newNode=cur;
//切换第二个节点
cur=next;
}
return newNode;
}