您好,欢迎来到外链网!
当前位置:外链网 » 站长资讯 » 专业问答 » 文章详细 订阅RssFeed

c语言单链表反转完整代码,单链表的逆转链表怎么写代码

来源:互联网 浏览:113次 时间:2023-04-08

为了面试中手撕代码,练习单链表的初始化

结点类的定义如下: public class ListNode { int val; ListNode next; public ListNode(int val, ListNode next) { this.val = val; this.next = next; }} 完整代码如下: public class Solution { public static void main(String[] args) { ListNode fourth=new ListNode(4,null); ListNode third=new ListNode(3,fourth); ListNode second=new ListNode(2,third); ListNode first=new ListNode(1,second); //创建链表 System.out.println("反转之前的链表:"); print(first); reverseList(first); System.out.println("反转之后的链表:"); print(fourth); } //实现单链表的打印 public static void print(ListNode head){ ListNode temp=head; while(temp!=null){ System.out.print(temp.val+" "); System.out.println(); temp=temp.next; } }//反转链表 public static ListNode reverseList(ListNode head) { //双指针 ListNode pre=null,cur=head; while(cur!=null){ ListNode tmp=cur.next; cur.next=pre; pre=cur; cur=tmp; } return pre; }}