标签:遇到 ati eve link reverse lis imp 定义 either
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; } };
【LeetCode】27.Linked List—Reverse Linked List l链表逆置
标签:遇到 ati eve link reverse lis imp 定义 either
原文地址:https://www.cnblogs.com/hu-19941213/p/11429659.html