leetcode206-反转链表
/** * 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* preNode = nullptr; ListNode* curNode = head; while(curNode && curNode->next){ ListNode* tmp = curNode->next; curNode->next = preNode; preNode = curNode; curNode = tmp; } if(curNode){ //此处一开始没注意可能为空数组的情况。 curNode->next = preNode; } return curNode; } };
javascript版本
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {ListNode} */ var reverseList = function(head) { let preNode = null; let curNode = head; while(curNode){ let temp = curNode.next; curNode.next = preNode; preNode = curNode; curNode = temp; } return preNode; };