为什么80%的码农都做不了架构师?>>>
//链表的定义
public class ListNode {int val;ListNode next = null;ListNode(int val) {this.val = val;}
}*/
//迭代
/*问题:1.输入为空2.只有一个结点3.头结点的特殊处理4.改变结点的next值时,链表会断开,怎么处理?5.翻转完成是新链表的头结点?6.迭代时 循环的终止条件?
*/
public class Solution {public ListNode ReverseList(ListNode head) {if(head==null||head.next==null){//解决问题1和2return head;}ListNode p=head.next;head.next=null; //解决问题3ListNode pre=head;ListNode tmp=p.next;//解决问题5:用于链表断开时,记录下一个链表//循环终止条件需要自己模拟翻转步骤,问题6while(p!=null){p.next=pre;pre=p;p=tmp;if(tmp!=null){tmp=tmp.next; } }head=pre;return head;}
}
//递归法
public class Solution {public ListNode ReverseList(ListNode head) {if(head==null||head.next==null){return head; }else{ListNode newHead=ReverseList(head.next);head.next.next=head;head.next=null;return newHead;}}
}