/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ publicclassSolution{ public ListNode reverseList(ListNode head){ if(head != null && head.next != null) { ListNode pivot = head; ListNode frontier = null; while(pivot!=null && pivot.next!=null){ frontier = pivot.next; pivot.next = pivot.next.next; frontier.next = head; head = frontier; } } return head; } }
解决方案4(Golang)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcreverseList(head *ListNode) *ListNode { var pre *ListNode = nil current := head fornil != current { now := current.Next current.Next = pre pre = current current = now } return pre }