leetcode解题之206 # Reverse Linked List Java版 (使用头插法反转链表)

206. Reverse Linked List


Reverse a singly linked list.

头插法反转链表

	// Definition for singly-linked list.
	public class ListNode {
		int val;
		ListNode next;
		ListNode(int x) {
			val = x;
		}

	}

public ListNode reverseList(ListNode head) {
		//头结点,不存储
		ListNode h=new ListNode(0);
		//指向下一个要遍历的结点,防止断链
		ListNode next;
		while(head!=null){
			next=head.next;
			//注意以下两句代码不能调换位置
			h.next=head;
			head.next=h.next;
			head=next;
		}
		return h.next;
	}


你可能感兴趣的:(leetcode,java,leetcode,206,Reverse,Linked,使用头插法反转链表)