Go语言版本
package main import . "nc_tools" func ReverseList( pHead *ListNode ) *ListNode { if pHead == nil { return nil } VirtualRoot := &ListNode{Val: 0} VirtualRoot.Next = pHead start := VirtualRoot.Next next := start.Next for next != nil { start.Next = next.Next next.Next = VirtualRoot.Next VirtualRoot.Next = next next = start.Next } return VirtualRoot.Next // write code here }
Java版本
import java.util.*; public class Solution { public ListNode ReverseList(ListNode head) { if(head == null){ return null; } // 设置虚拟节点 ListNode virtualRoot = new ListNode(0); virtualRoot.next = head; // start节点保持不变,一直指向head ListNode start = head; ListNode next = head.next; while(start.next != null){ start.next = next.next; next.next = virtualRoot.next; virtualRoot.next = next; next = start.next; } return virtualRoot.next; } }
全部评论
(3) 回帖