问题:链表逆序
解决方案:依次遍历链表节点,并直接逆序
流程:
1,备份head->next;
2,修改head->next=new_head;
3,移动head和new_head;
1,
*next=&2 //保存2元素所在地址,以免丢失
new_head->next=NULL //创建新链表
2,
head->next=new_head //反转
3,
new_head=head; //移动new_head
head=next; //移动head
代码如下:
/**
* 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 *new_head = NULL; //指向新链表表头的指针
while(head){
ListNode *next = head->next;//备份head->next
head->next = new_head;//反转
new_head = head;//移动
head = next;//移动
}
return new_head;
}
};