反转一个单链表
LeetCode:反转一个单链表
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
这个题的解法不止一种,可以直接给出三个指针
mid front after
初始化:front=NULL,after=NULL, mid=head(1);
第一次的时候:
after=mid->next=2;
mid ->next=front=NULL;
front=mid=1;
mid=after=2;
然后 :
用三个指针以此循环交换······
接下来,用代码实现:
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* reverseList(struct ListNode* head)
{
struct ListNode*front=NULL;
struct ListNode*mid=NULL;
struct ListNode* after=NULL;
mid=head;
if(head==NULL)
{
return NULL;
}
else
{
while(mid->next)
{
after=mid->next;
mid->next=front;
front=mid;
mid=after;
}
}
mid->next=front;
return mid;
}