反转链表
leetcode 题目:206,假设输入:1–>2–>3–>4–>5,输出:5–>4–>3–>2–>1
解法:双指针法
初始化:
ListNode *tmp, *newHead = NULL;
ListNode *cur = head;
如果head不为空,第一次循环:
tmp = NULL;
newHead = head;
cur = cur -> next;
newHead -> next = NULL;
完整代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *newHead = NULL, *cur = head, *tmp;
while(cur)
{
tmp = newHead;
newHead = cur;
cur = cur -> next;
newHead -> next = tmp;
}
return newHead;
}
};
}
return newHead;
}
};