为了面试中手撕代码,练习单链表的初始化
结点类的定义如下:
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;
}
}