Reverse a linked list

本文介绍了一种反转链表的方法,提供了两种实现方案:一种是通过调整节点指针来完成反转,另一种是使用栈来反转链表中的元素值。这两种方法都适用于给定的链表节点头,无需额外输入。

Problem Statement

This challenge is part of a tutorial track by MyCodeSchool and is accompanied by a video lesson.

You’re given the pointer to the head node of a linked list. Change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty.

Input Format 
You have to complete the Node* Reverse(Node* head) method which takes one argument - the head of the linked list. You should NOT read any input from stdin/console.

Output Format 
Change the next pointers of the nodes that their order is reversed and return the head of the reversed linked list. Do NOT print anything to stdout/console.

Sample Input

NULL 
2 --> 3 --> NULL

Sample Output

NULL
3 --> 2 --> NULL

Explanation 
1. Empty list remains empty 

2. List is reversed from 2,3 to 3,2

/*
  Insert Node at the end of a linked list 
  head pointer input could be NULL as well for empty list
  Node is defined as 
  class Node {
     int data;
     Node next;
  }
*/
    // This is a "method-only" submission. 
    // You only need to complete this method. 

//三个指针,画图,q始终指向头,head没动,p在head后面
Node Reverse(Node head) {
    
    if(head==null||head.next==null)
        return head;

    Node p=new Node();
    p=head.next;
    Node q=new Node();
    q=head;
    while(p!=null){
        head.next=p.next;
        p.next=q;
        q=p;
        p=head.next;
    }
    return q;
}
//用栈,对链表的值替换
Node Reverse(Node head) {
    if(head==null||head.next==null)
        return head;

    Stack<Integer> s=new Stack<>();
    Node p=new Node();
    p=head;
    while(p!=null){
        s.push(p.data);
        p=p.next;
    }
    p=head;
    while(p!=null){
        p.data=s.pop();
        p=p.next;
    }
    return head;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值