Reverse Linked List
Reverse a singly linked list.
Hint:
代码:
A linked list can be reversed either iteratively or recursively. Could you implement both?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode *pReversedHead = NULL;
struct ListNode *pNode = head;
struct ListNode *pPrev = NULL;
while (pNode != NULL) {
struct ListNode *pNext = pNode->next;
if (pNext == NULL)
pReversedHead = pNode;
pNode->next = pPrev;
pPrev = pNode;
pNode = pNext;
}
return pReversedHead;
}
原题地址:
https://leetcode.com/problems/reverse-linked-list/