剑指Offer--【反转链表】--java

题目描述:
输入一个链表,反转链表后,输出新链表的表头。

解题思路:
根据下图,先给定一个空的链表newList,然后判断传入的链表head是不是空链表或者链表元素只有一个,如果是,直接返回就可以。如果不是,则对链表进行迭代,然后给一个临时变量temp存储head.next,然后改变head.next的指向newList,然后把head赋值给newList,接着让head等于临时变量temp,就这样一直迭代完整个链表,返回newList就可以
在这里插入图片描述
运行代码:
/*
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode newList=null;
ListNode temp=null;
if(head == null||head.next==null){
return head;
}
while(head!=null){
temp=head.next;
head.next=newList;
newList=head;
head=temp;
}
return newList;
}
}
运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43689040/article/details/87825744
今日推荐