题解 | #反转链表#

反转链表

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/

/**
思路:用三个指针对链表进行遍历,每访问一个节点就修改该节点的next指针,
用temp1表示当前节点的前一个节点,temp表示当前节点的下一个节点,head表示当前节点
          temp = head.next;
          head.next = temp1;
          temp1 = head;
          head = temp;
当head.next为空时,表示到达最后一个节点,循环结束,修改head.next=temp1,返回head
*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
      if(head == null){
        System.out.println("{}");
        return head;
      }else{
        ListNode temp = null;//表示当前节点的下一个节点
        ListNode temp1 = null;//表示当前节点的上一个节点
        while(head.next != null){//head表示当前节点
          temp = head.next;
          head.next = temp1;
          temp1 = head;
          head = temp;
        }
        head.next = temp1;
        return head;
      }
      
    }
}

全部评论

相关推荐

求面试求offer啊啊啊啊:把华北改为华南再试一试,应该就没啥问题了。改完可能都不用投,别人主动联系了。
点赞 评论 收藏
分享
04-22 15:13
已编辑
Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务