题目:
分别实现反转单向链表和反转双向链表的函数
要求:
分别实现反转单向链表和反转双向链表的函数
要求:
如果链表长度为N,时间的复杂度要求为O(N),额外空间的复杂度O(1)
示例代码:
//反转单向链表 public class Node{ public int value; public Node next; public Node(int data){ this.value = data; } } public Node reverseList(Node head){ Node pre = null; Node next = null; while(head != null){ next = head.next; head.next = pre; pre = head; head = next; } return pre; }
// 反转双向链表 public class DoubleNode{ public int value; public DoubleNode last; public DoubleNode next; public DoubleNode(int data){ this.value = data; } } public DoubleNode reverseList(DoubleNode head){ DoubleNode pre = null; DoubleNode next = null; while(head != null){ next = head.next; head.next = pre; head.last = next; pre = head; head = next; } return pre; }