反转链表

将一个链表反转输出,链表没有head结点。

思路

因为没有头节点,不能用头插法来实现反转,但可以采用差不多的思想。
ListNode的结构

public class ListNode {
    int  val;
    ListNode next = null;
    
    public ListNode(int val) {
        this.val = val;
    }
}

算法具体代码

public ListNode ReverseList(ListNode head) {
    ListNode front, nextNode;
    if (head == null) {
        return null;
    }
    front = head;
    while (head.next != null) {
         nextNode = head.next;
         head.next = nextNode.next;
         nextNode.next = front;
         front = nextNode;
     }
    return front;
}

代码中利用了nextNode来存储当前结点的下一个结点,已经新的头节点front。
假设输入的链表为1 -> 2 -> 3 -> 4 -> 5,那么head结点和front结点的值为1,经过head.next = nextNode.next之后,head结点的下一个结点由2变为了3,nextNode.next = front,链表就变为了2 -> 1-> 3 -> 4 -> 5,再修改front结点为2。这样经过一次遍历,链表反转就完成了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容