欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单链表的反转(包括带头节点和不带头节点)

程序员文章站 2022-03-15 17:37:26
...

带头节点

package auguest;

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

	ListNode ReverseLinkList(ListNode head)
	{
		ListNode p,q,pr;
		 p=head.next;
		 q=null;
		 head.next=null;
		 while(p!=null)
		 {
		     pr=p.next;
			 p.next=q;
			 q=p;
			 p=pr;
		 }
		 
		 head.next=q;
		 
		 return head;
	}
	
}

不带头节点:


public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null) return null;
        
        ListNode pre = null;
        ListNode next = null;
        
        while(head != null) {
            //反转当前节点的指向
            next = head.next;
            head.next = pre;
            //移动指针
            pre = head;
            head = next;
        }
        return pre;
    }
}