数据结构与算法Java版:单链表的反转

public class LinkedList {
	 Node head;
	 public static void main(String[] args) {		 	     
	        LinkedList list=new LinkedList();
	        list.add(1);
	        list.add(2);
	        list.add(3);
	        list.add(4);
	        list.add(5);
	        printList(list.head);
	        printList(reverse(list.head));
	    }
	 	//头插法建立链表,头节点不为空
	    public void add(int num) {
	    	Node node = new Node(num);
	    	if (this.head == null) {
	            this.head = node;
	        } else { 
	            node.next = this.head; 
	            this.head = node;     
	        }	    	
	    }
		//链表反转
		public static Node reverse(Node head) {
			Node pre = null;
	        Node next = null;
	        while (head != null) {
	            next = head.next;
	            head.next = pre;
	            pre = head;
	            head = next;
	        }
	        return pre;
		}

	    public static void printList(Node p) {
	        while(p != null){
	            System.out.printf("%d ",p.val);
	            p = p.next;
	        }
	        System.out.println();
	    }
	}
	
class Node {
    int val;
    Node next = null;
    
    public Node() {
    	
    }

    public Node(int val) {
        this.val = val;
    }
}

输出:
在这里插入图片描述
稍微解释一下过程:
第一次循环:
head=1 1.next=null
第二次循环:
head=2 2.next=1
第三次循环:
head=3 3.next=2
第四次循环:
head=4 4.next=3
第五次循环:
head=5 5.next=4
是不是就串起来了呀。最后一次循环pre=5,成为新的头结点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值