第一种,适用于带头结点得链表:
代码如下:
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* ReverseList(struct ListNode* head ) {
struct ListNode* mid; //中间的结点,用来操作的
struct ListNode* front; //前面的结点
struct ListNode* rear; //后面的结点
rear=head->next;
mid=NULL:
front=NULL:
while(mid){
front=mid;
mid=rear;
rear=rear->next;
mid->next=front;
}
head->next=mid;
return head;
}
图解代码:
?第二种,没有头结点的链表:
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* ReverseList(struct ListNode* head ) {
struct ListNode* front;
struct ListNode* rear;
front=NULL;
rear=NULL;
while(head){
rear=head->next;
head->next=front;
front=head;
head=rear;
}
return front;
}
图解代码:
?
|