Niuke.com's sword refers to Offer - reverse linked list

Topic description

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

Problem solving ideas

Three pointers can be used to point to the currently traversed node (pointer cur), its previous node (pointer pre) and the next node (pointer next). In the traversal process, first record the next node of the current node, then set cur->next=pre, then set pre=cur, cur=next, and so on, until the next node of the current node is NULL, it represents the current When the node is reversed, the head node is gone.

code

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if (pHead == NULL || pHead-> next == NULL)
            return pHead;
        ListNode * pre = pHead;
        ListNode * cur = pHead-> next;
        ListNode* next = cur->next;
        pre->next = NULL;
        while( 1 )
        {
            cur->next = pre;
            pre = cur;
            cur = next;
            if( next == NULL )
                break;
            next = next->next;
        }
        return pre;
    }
};

Notice

反转后,原本的头结点变为最后一个节点,要令其next指向NULL
注意输入的链表头指针为nullptr或者整个链表只有一个节点的情况

Guess you like

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