Sharing my c++ code without using recursion method


  • 0
    S
    if (!head || !(head->next) )	return head;
    ListNode *cur = head,*next = head->next;
    head = head->next;//说明总个数不止1一个,改变head
    while(next){
    	next = next->next;//next->3
    	cur->next->next =cur;//2->1
    	
    	if(!next || !(next->next)) {
    	cur->next = next;//1->3;
    	return head;}
    
    	cur->next = next->next;//否则 1->4
    	cur = next;// cur ->3
    	next = next->next;//next->4  最终 2->1->4 3->4->5->6...
    }
    return head;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.