写循环体的技巧-----循环不变式(loop invariant)

循环不变式是一种条件式(必须满足的条件,对循环而言是保持不变的,无论循环执行了多少次),循环语句没执行一次,就要求中间的结果必须符合不变式的要求。

  • (1)进入循环语句时,不变式必须成立;
  • (2)循环语句的循环体不能破坏不变式。也就是说,循环体开始循环时不变式成立,结束时也必须成立;
  • (3)如果循环语句终止时不变式,依旧成立,那么至少说明,循环在保持循环不变式上没有犯错。          
    // (**) 不变式在进入循环之前必须成立
    while () {
        // 循环体开始
        ...
        // 循环体结束
        // (**) 不变式在此处也必须成立
    }
    以链表反转为例
  • import java.util.Arrays;
    
    public class LinkedListReverse {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Solution test2=new Solution();
    		ListNode head=test2.createLinkedList(Arrays.asList(1,2,3,4,6,5,7));
    		LinkedListReverse test=new LinkedListReverse();
    		head=test.linkedListReverse(head);
    		ListNode.printLinkedList(head);
    	}
    	public ListNode linkedListReverse(ListNode head){
    		//newhead 代表反转过的新head loop invariant1
    		ListNode newhead = null;
    		//curhead 代表未反转的head loop invariant2
    		ListNode curhead=head;
    		while(curhead!=null)
    		{
    			//循环体执行前必须满足loop invariant 即newhead 代表反转过的新head,curhead 代表未反转的head 
    			ListNode next=curhead.getNext();
    			curhead.setNext(newhead);
    			newhead=curhead;
    			curhead=next;
    			//循环体执行后也必须满足loop invariant 即newhead 代表反转过的新head,curhead 代表未反转的head
    		}
    		//跳出循环后也必须满足loop invariant 即newhead 代表反转过的新head,curhead 代表未反转的head
    		return newhead;
    	}
    }


  •                                                                                                                                                  

猜你喜欢

转载自blog.csdn.net/ustcyy91/article/details/80375819
今日推荐