LeetCode|C++|206. Reverse Linked List

基本思路:遍历链表,不断把节点摘下来插到链表头部,记得不要断链

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
	ListNode* reverseList(ListNode* head) {
		if (head == NULL || head->next == NULL)
			return head;
		ListNode *L = new ListNode(0);
		L->next = head;
		ListNode *p = head->next, *tail = head;
		while (p != NULL){
			tail->next = p->next;
			p->next = L->next;
			L->next = p;
			p = tail->next;

		}
		return L->next;
	}
};

 

你可能感兴趣的:(leetcode,c++,leetcode,c++)