Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
思路:
重塑链表,将首结点逐个后移,移动过程中遇到的结点都依次结到链表开头。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode *p=head; //定义指向头节点的指针 if(p==NULL) return NULL; //使用前判断是否为空指针 ListNode *q=p->next; //定义第二个指针始终指向P的next while(p!=NULL&&q!=NULL) { p->next=q->next; q->next=head; head=q; q=p->next; } return head; } };
原文地址:https://www.cnblogs.com/hu-19941213/p/11429659.html
时间: 2024-09-30 10:04:46