剑指offer 16. 反转链表
2017-05-11 15:17
316 查看
class ListNode { int data; ListNode next; } // 题目:链表翻转 // 解法:设立三个标志直接进行翻转 public class Main { public static void main(String[] args) { ListNode n1 = new ListNode(); ListNode n2 = new ListNode(); ListNode n3 = new ListNode(); ListNode n4 = new ListNode(); ListNode t1 = new ListNode(); ListNode t2 = new ListNode(); ListNode t3 = new ListNode(); ListNode t4 = new ListNode(); n1.data = 1; n2.data = 3; n3.data = 5; n4.data = 7; t1.data = 2; t2.data = 4; t3.data = 6; t4.data = 8; n1.next = n2; n2.next = n3; n3.next = n4; n4.next = t1; t1.next = t2; t2.next = t3; t3.next = t4; ListNode result = reverseList(n1); while(result!=null){ System.out.println(result.data); result = result.next; } } public static ListNode reverseList(ListNode node) { if(node == null || node.next == null){ return node; } ListNode pre = null; //前序结点先设置为空 ListNode point = node; //操作结点为头节点 ListNode pos = point.next; //pos为当前节点下一个节点 while(pos!=null){ //当pos结点为空则跳出循环 point.next = pre; pre = point; point = pos; pos = point.next; } point.next = pre; //使当前节点与前序结点相连 return point; //并返回当前节点 } }
相关文章推荐
- 剑指Offer面试题16反转链表(递归和非递归),面试题17合并两个排序的链表(递归)
- 《剑指Offer》读书笔记--面试题16:反转链表
- 剑指Offer面试题16(Java版):反转链表
- 剑指offer面试题16:反转链表
- (剑指Offer)面试题16:反转链表
- 剑指offer面试题16-反转链表
- 剑指Offer系列-面试题16:反转链表
- 《剑指offer》面试题16—反转链表
- 剑指offer 面试题16 反转链表
- 剑指offer——面试题16:反转链表
- 《剑指Offer》面试题16:反转链表
- (未完成)《剑指offer》(面试题16):反转链表
- 【剑指offer系列】 反转链表___16
- 《剑指Offer》学习笔记--面试题16:反转链表
- 面试题16:反转链表
- 剑指offer 面试题16 反转链表-Java实现
- 剑指offer系列源码-反转链表
- 面试16: 反转链表
- 面试题16:反转链表
- 【剑指offer】题16:反转链表