单向链表反转

package com.wym;

/**
 * @Author 911
 * @Create 2021/08/01 17:02
 * @Description:
 */
public class demo1 {
    public static void main(String[] args) {

        node node = new node(1, new node(2, new node(3, null)));

        com.wym.node reverseList1 = node.reverseList1(node);

        System.out.println(reverseList1);
    }
}
class node{
    int val;
    node next;

    public node() {
    }

    public node(int val, node next) {
        this.val = val;
        this.next = next;
    }

    @Override
    public String toString() {
        return "node{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }

    public node reverseList1(node head){

        node temp = new node();
        temp.next = head;

        node prev = temp.next;
        node pcur = prev.next;

        while (pcur != null){



            prev.next = pcur.next;
            pcur.next = temp.next;
            temp.next = pcur;
            pcur=prev.next;




        }


        return temp.next;
    }
}

背写一边:

public node revent(Node head){
  Node temp = new Node();
  temp.next=head;
  Node prev = temp.next;
  Node pcur = prev.next;  
  
while(pcul!=null){
   prev.next = pcur.next;
  pcur.next=temp.next;
  temp.next = pcur;
  pcur=prev.next;
  }
   return temp.next;
}

 

posted on 2021-10-03 19:00  爱你的小宝贝  阅读(49)  评论(0)    收藏  举报