LeetCode—reverse-linked-list
链接:
https://leetcode.com/problems/reverse-linked-list/
题目:
Reverse a singly linked list
单链表反转
方法一:
每次都将第二个结点提到最前面,
Solution:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* current; // 指向当前结点
struct ListNode* pnext; // 待反转的结点,
struct ListNode* prev; // next 的后继
if ((NULL == head) || (NULL == head->next))
{
return head;
}
current = head;
pnext = current->next;
current->next = NULL;
while (pnext != NULL)
{
prev = pnext->next;
pnext->next = current; // 将该结点放到最前面
current = pnext;
pnext = prev;
}
head = current; // current赋给头结点
return head;
}
方法二:
方法一的改进版,思路是一样的,都是将第二个结点提到最前面。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* current;
struct ListNode* pnext;
if (NULL == head)
{
return NULL;
}
current = head;
while (NULL != current->next)
{
pnext = current->next;
current->next = pnext->next;
pnext->next = head; // 将该结点提到最前面
head = pnext;
}
return head;
}
方法三:
新建一个单链表,每次都将原list中的结点放到newlist的后面。代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
struct LinkNode* newhead; //新链表的头结点
struct LinkNode* tmp; //指向head的第一个结点,也就是要摘除的结点
//参数为空或者内存分配失败则返回NULL
if (head == NULL || (newhead = (struct ListNode*)malloc(sizeof(ListNode))) == NULL)
{
return NULL;
}
//初始化newhead
newhead->val = head->val;
newhead->next = NULL;
//依次将L的第一个结点放到newhead的第一个结点位置
while (head->next != NULL)
{
tmp = newhead->next; //保存newhead中的后续结点
newhead->next = head->next;//将head的第一个结点放到newhead中
head->next = head->next->next; //从head中摘除这个结点
newhead->next->next = tmp;//恢复newhead中后续结点的指针
}
//原头结点应该释放掉,并返回新头结点的指针
free(head);
return newhead;
}