Android-Daily-Interview
Android-Daily-Interview copied to clipboard
2019-07-03:如何反转一个单链表?
把屏幕倒过来。。。
把屏幕倒过来。。。
牛皮,牛皮,牛皮,三连
https://blog.csdn.net/lwkrsa/article/details/82015364
如果没记错的话,大概过程是这样 ABC temp=A.next A.next=temp.next temp.next=A 然后循环
//递归 private static ListNode reverse(ListNode head) { if (head.next == null) return head; ListNode reversedListNode = reverse(head.next); head.next.next = head; head.next = null; return reversedListNode; }
从链表第2个开始,进行排序比较;知道n-1结束;最后将比较过的数据作为一个整体与第一个比较进行比较,进行反转。例如:abcd四个数据; abcd愿数据 acbd第一次反转排序 adcb第二次反转排序 dcba第三次反转排序
https://blog.csdn.net/lwkrsa/article/details/82015364
入栈出栈
双指针,一个指向头,一个指向尾,交换
先入栈在出栈
思路:定义3个节点分别是preNode, curNode, nextNode. 先将curNode的next赋值给nextNode, 再curNodel的next指向preNode.至此curNode的指针调整完毕。 然后往后移动curNode, 将curNode赋值给preNode,将nextNode赋值给curNode,如此循环到curNode==null为止
代码: public static Node reverseListNode(Node head){ //单链表为空或只有一个节点,直接返回原单链表 if (head == null || head.getNext() == null){ return head; } //前一个节点指针 Node preNode = null; //当前节点指针 Node curNode = head; //下一个节点指针 Node nextNode = null;
while (curNode != null){
nextNode = curNode.getNext();//nextNode 指向下一个节点
curNode.setNext(preNode);//将当前节点next域指向前一个节点
preNode = curNode;//preNode 指针向后移动
curNode = nextNode;//curNode指针向后移动
}
return preNode;
}
可以用头插法,将原来的单链表逆置
