Sword refers to offer - input a linked list, after reversing the linked list, output all elements of the linked list

Q: Input a linked list, after reversing the linked list, output all elements of the linked list.

A: 1. First add a head node before the head node of the original linked list;

      2. Use the head insertion method to reverse all nodes after the newly added head node.

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if (NULL == pHead || NULL == pHead-> next)
        {
            return pHead;
        }
        
        ListNode *p, *q;
        ListNode *tmp = new ListNode(0);
        tmp->next = pHead;
        p = tmp->next;
        tmp->next = NULL;
        
        while(p)
        {
            q = p
            p = p->next;
            q->next = tmp->next;
            tmp->next = q;
        }
        return q;
    }
};


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325965353&siteId=291194637