Prove safety offer: reverse list

One, Title Description

  After entering a list inverted list, the new list of the output header.

 

Second, the idea

  The use of iterative thinking, traverse the list from front to back. It defined three pointers, pointing to three neighboring nodes. Rotating front two nodes, and then successively three backward pointer. Until the second pointer is NULL. Finally, the processing chain end to end nodes.

  

 

 

 

 

 

 

 

 

 Third, the code

 

public class 反转链表 {
	
	public class ListNode {
	    int val;
	    ListNode next = null;

	    ListNode(int val) {
	        this.val = val;
	    }
	}
	
    public ListNode ReverseList(ListNode head) {
    	if(head==null||head.next==null){
    		return head;
    	}
    	else{
    		ListNode p1 = head;
    		ListNode p2 = p1.next;
    		ListNode p3 = p2.next;
    		
    		while(p2!=null){
    			p3 = p2.next;
    			p2.next = p1;  //第二个结点指向第一个结点进行反转
    			p1 = p2;	   //第一个结点后移	
    			p2 = p3;	   //第二个结点后移
    		}
    		
    		head.next = null;
    		head = p1;
    		return head;
    	}
    }
}

  

Guess you like

Origin www.cnblogs.com/blzm742624643/p/12237884.html