zoukankan      html  css  js  c++  java
  • 反转链表


    输入一个链表,反转链表后,输出新链表的表头


    解法一

    说起反转,第一个想到的肯定是利用栈先进后出的特性。这道题当然可以用栈来实现,但是对于注释中那一块不是很明白,先放着,如果有大佬知道的话求解答

    public class Solution {
    	public ListNode ReverseList(ListNode head) {
    		if (head == null)
    			return null;
    		
    		Stack<ListNode> stack = new Stack<ListNode>();
    		ListNode temp = head;
    		do {
    			stack.push(temp);
    			temp = temp.next;
    		} while (temp != null);
    		//如果这里的头结点的next要不置为空,就会导致遍历时无限循环
    		head.next = null;
    	
    		ListNode root = stack.pop();
    		ListNode node = root;
    		while (!stack.isEmpty()) {
    			node.next = stack.pop();
    			node = node.next;
    		}
    		return root;
    	}
    }
    

    解法二

    最好的办法就是利用双指针的方式

    public class Solution {
        public ListNode ReverseList(ListNode head) {
            if(head == null)
                return null;
            // head为当前节点,如果当前节点为空的话,那就什么也不做,直接返回null;
            ListNode pre = null;
            ListNode next = null;
            // 当前节点是head,pre为当前节点的前一节点,next为当前节点的下一节点
            // 需要pre和next的目的是让当前节点从pre->head->next1->next2变成pre<-head next1->next2
            // 即pre让节点可以反转所指方向,但反转之后如果不用next节点保存next1节点的话,此单链表就此断开了
            // 所以需要用到pre和next两个节点
            // 1->2->3->4->5
            // 1<-2<-3 4->5
            while(head!=null){
                // 做循环,如果当前节点不为空的话,始终执行此循环,此循环的目的就是让当前节点从指向next到指向pre
                // 如此就可以做到反转链表的效果
                // 先用next保存head的下一个节点的信息,保证单链表不会因为失去head节点的原next节点而就此断裂
                next = head.next;
                // 保存完next,就可以让head从指向next变成指向pre了,代码如下
                head.next = pre;
                // head指向pre后,就继续依次反转下一个节点
                // 让pre,head,next依次向后移动一个节点,继续下一次的指针反转
                pre = head;
                head = next;
            }
            // 如果head为null的时候,pre就为最后一个节点了,但是链表已经反转完毕,pre就是反转后链表的第一个节点
            // 直接输出pre就是我们想要得到的反转后的链表
            return pre;
        }
    }
    

  • 相关阅读:
    配置磁盘映射(在服务器和eclipse 中)
    服务器mysql授权连接用户
    validationEngine验证的使用
    Remove '@override' annotation解决办法
    js页面报错javax.servlet.jsp.PageContext cannot be resolved to a type解决
    如何正确使用log4j
    Log4j使用教程
    windows系统修改mysql端口的方法
    on条件与where条件的区别
    mybaits错误解决:There is no getter for property named 'id' in class 'java.lang.String'
  • 原文地址:https://www.cnblogs.com/Yee-Q/p/13741269.html
Copyright © 2011-2022 走看看