常见算法 - 链表相关:反转链表

链表只要注意不要丢失掉对节点引用;多可设置虚拟头结点简化引用的处理。

1.反转列表(leetcode206)

public class L206ReverseLinkedList {		
	public static ListNode reverseList(ListNode head) {
		if(head == null){
			return null;
		}
		ListNode pre = null;
		ListNode curr = head;
		ListNode next = head.next;
		while(curr.next!=null){
			next = curr.next;
			curr.next = pre;
			pre = curr; 
			curr = next;
		}
		curr.next = pre;
		ListNode res = curr;
		return res;
    }
}


class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

猜你喜欢

转载自blog.csdn.net/b9x__/article/details/80217615